您的位置:首页 > Web前端 > JQuery

WEB前端技巧之JQuery为动态添加的元素绑定事件.md

2016-08-08 13:27 726 查看

jquery 为动态添加的元素绑定事件


如果直接写click函数的话,只能把事件绑定在已经存在的元素上,不能绑定在动态添加的元素上


可以用delegate来实现

.delegate( selector, eventType, handler )


例如示例:

$('someUlSelector').delegate('someLiSelector','click',function(){


//codes...


//$(this) for the current jquery instance of the element


});


jQuery 事件 - delegate() 方法

jQuery的delegate有好几个缺憾


因为sizzle少提供了以refEl为参考、一个按selector来筛选els的filter(els,selector,refEl)的功能,jq需要自己去实现类似的功能。



其一:selector是基于
: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});


其二:多个祖先满足条件时,只触发了target的closest的那一个祖先,而不是都触发。—-想不通jquery为什么要采用这个策略

示例代码如

<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>


其三:与sizzle一样,可能是没有回溯,在某些情况下有bug。

例如,当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>


中文API的解释delegate



来自为知笔记(Wiz)



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: