標籤:
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)
WEB前端技巧之JQuery為動態添加的元素繫結事件