使用jQuery委托事件处理程序时,如何获取后代选择器? [英] When using a jQuery delegated event handler, how do I get the descendant selector?
问题描述
使用jQuery委托事件处理程序时,如何获取后代选择器?例如,在下表中,我想选择被单击的表行:
When using a jQuery delegated event handler, how do I get the descendant selector? For example, in the following table, I want to select the table row that was clicked:
<div id='timeline'>
<table>
<tr data-somedata=5><td>First Row</td></tr>
<tr data-somedata=100><td>Another row</td></tr>
</table>
</div>
表是动态添加的,所以我使用的是委托事件处理程序。
The table is added dynamically, so I'm using a delegated event handler.
$("#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元素?
How can I select the tr element using the above delegated event handler?
此外,如果某人有一个只有JavaScript的解决方案,那也会很棒。
Also, if someone has a JavaScript only solution, that would be great too.
推荐答案
我把解决方案(我在评论部分中提到的)用于帮助未来的读者。
I put the solution (that I mentioned in comment section) to helping future readers.
你传递了 jQuery对象
作为选择器
,您需要将代码更改为以下内容,然后 $(this)
将是 tr
:
You passed jQuery object
as selector
, you need to change the code to following, then $(this)
will be the tr
:
$('#timeline').on('click', 'tr', function(event){
var $tr = $(this);
// play with $tr
});
关于的更多信息
此处: .on()
More about on
here: .on()
这篇关于使用jQuery委托事件处理程序时,如何获取后代选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!