<body>
<div>
<span>123</span><button>添加</button>
</div>
</body>
jquery:
$(function(){
//定义测试函数
function foo(){
alert($(this).text())}
//已有元素
$("div span").on(‘click‘,foo)
//点击按钮添加新元素
$("div button").click(function(){
$("div").append("<span>123</span>")
})//给新元素绑定事件 $("div").delegate(‘span‘,‘click‘,foo) //$("div").undelegate(‘click‘) })
这样就可以为添加的新元素绑定事件,并且原有的span元素会弹出两次文本内容,证明delegate也给匹配到的当前的元素绑定了事件。
如果想要消除绑定很简单:
$("div").undelegate(‘click‘)
删除由delegate委派绑定的事件,不是通过delegate委派的事件则不会删除。
原文:http://blog.51cto.com/14094286/2333054