[英]When using a jQuery delegated event handler, how do I get the descendant selector?
使用jQuery委托事件处理程序时,如何获取后代选择器? 例如,在下表中,我要选择被单击的表行:
<div id='timeline'>
<table>
<tr data-somedata=5><td>First Row</td></tr>
<tr data-somedata=100><td>Another row</td></tr>
</table>
</div>
该表是动态添加的,因此我正在使用委托事件处理程序。
$("#timeline").on('click', $("tr"), function(event){
console.debug($(this)); // This selects the entire #timeline
console.debug(event.target); // This selects the <td> element, not the <tr>
});
如何使用上面的委托事件处理程序选择tr元素?
另外,如果某人只有JavaScript解决方案,那也很好。
我将解决方案( 在评论部分中提到 )用于帮助将来的读者。
您将jQuery object
作为selector
传递,您需要将代码更改为以下代码,然后$(this)
将为tr
:
$('#timeline').on('click', 'tr', function(event){
var $tr = $(this);
// play with $tr
});
有关更多信息on
访问: .on()
您的代码中几乎没有错误。
1.its `timeline` not `#timeline`
2.you can simply refer as tr it should not be $('tr')
除了这你的代码是好的
$("timeline").on("click","tr",function(){ alert($(this).attr('data-somedata')); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <timeline> <table> <tr data-somedata=5><td>First Row</td></tr> <tr data-somedata=100><td>Another row</td></tr> </table> </timeline>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.