标签:
如果直接写click函数的话,只能把事件绑定在已经存在的元素上,不能绑定在动态添加的元素上
可以用delegate来实现
.delegate( selector, eventType, handler )
例如示例:
$(‘someUlSelector‘).delegate(‘someLiSelector‘,‘click‘,function(){
//codes...
//$(this) for the current jquery instance of the element
});
jQuery的delegate有好几个缺憾
因为sizzle少提供了以refEl为参考、一个按selector来筛选els的filter(els,selector,refEl)的功能,jq需要自己去实现类似的功能。
:root
的,而不是:scope
的。所以,在写代码时,需要带上 scrope
的定位部分。—-注::root
指document根节点,:scope
指代理节点示例代码如
<HTML><HEAD><TITLE>JK Test</TITLE>
<METAcontent="text/html; charset=gb2312"http-equiv=Content-Type>
<scriptsrc="http://common.cnblogs.com/script/jquery.js"type="text/javascript"></script>
<style>
div{border:1px solid balck;padding:5px;margin:2px;}
</style>
</HEAD>
<body>
<divid="div1">div1
<divid="div1_1">div1_1
<divid="div1_1_1">div1_1_1
<spanstyle="color:red">span</span>
</div>
</div>
<divid="div1_2">div1_2
</div>
</div>
</body>
<scripttype="text/javascript">
$(‘#div1‘).delegate(‘#div1>*‘,‘click‘,function(){alert(this.innerHTML);});//点击div1_1,div1_2或时,都有效。
</script>
</HTML>
//例如,代理div1的儿子,需要这样写:
$(‘#div1‘).delegate(‘#div1>*‘,‘click‘,fun});
//而不是这样写:
$(‘#div1‘).delegate(‘>*‘,‘click‘,fun});
示例代码如
<HTML><HEAD><TITLE>JK Test</TITLE>
<METAcontent="text/html; charset=gb2312"http-equiv=Content-Type>
<scriptsrc="http://common.cnblogs.com/script/jquery.js"type="text/javascript"></script>
<style>
div{border:1px solid balck;padding:5px;margin:2px;}
</style>
</HEAD>
<body>
<divid="div1">div1
<divid="div1_1">div1_1
<divid="div1_1_1">div1_1_1
<spanstyle="color:red">span</span>
</div>
</div>
<divid="div1_2">div1_2
</div>
</div>
</body>
<scripttype="text/javascript">
$(‘body‘).delegate(‘div‘,‘click‘,function(){alert(this.innerHTML);});//点击id1_1_1时,应该同时代理到三个div的点击
</script>
</HTML>
例如,当span有多个祖先是div时,这个代理会失效:$(‘body‘).delegate(‘body>div span‘,‘click‘,fun;});
示例代码如
<HTML><HEAD><TITLE>JK Test</TITLE>
<METAcontent="text/html; charset=gb2312"http-equiv=Content-Type>
<scriptsrc="http://common.cnblogs.com/script/jquery.js"type="text/javascript"></script>
<style>
div{border:1px solid balck;padding:5px;margin:2px;}
</style>
</HEAD>
<body>
<divid="div1">div1
<divid="div1_1">div1_1
<divid="div1_1_1">div1_1_1
<spanstyle="color:red">span</span>
</div>
</div>
<divid="div1_2">div1_2
</div>
</div>
</body>
<scripttype="text/javascript">
$(‘body‘).delegate(‘body>div span‘,‘click‘,function(){alert(this.innerHTML);});//点击span时,应该出现alert的
</script>
</HTML>
标签:
原文地址:http://www.cnblogs.com/pangxiansheng/p/4c7cf226777cb2a2cfb214480a166307.html