Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用jQuery委托事件处理程序时,如何获取子体选择器?_Javascript_Jquery_Javascript Events_Event Handling - Fatal编程技术网

Javascript 使用jQuery委托事件处理程序时,如何获取子体选择器?

Javascript 使用jQuery委托事件处理程序时,如何获取子体选择器?,javascript,jquery,javascript-events,event-handling,Javascript,Jquery,Javascript Events,Event Handling,使用jQuery委托事件处理程序时,如何获取子体选择器?例如,在下表中,我想选择单击的表行: <div id='timeline'> <table> <tr data-somedata=5><td>First Row</td></tr> <tr data-somedata=100><td>Another row</td></tr>

使用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>
});
$(“#时间线”)。在('click',$('tr')上,函数(事件){
console.debug($(this));//这将选择整个#时间线
console.debug(event.target);//这将选择元素,而不是
});
如何使用上述委托事件处理程序选择tr元素

另外,如果有人有一个只使用JavaScript的解决方案,那也太好了。

我把这个解决方案(我在评论部分提到)用于帮助未来的读者

您将
jQuery对象
作为
选择器
传递,您需要将代码更改为以下内容,然后
$(此)
将成为
tr

$('#timeline').on('click', 'tr', function(event){
    var $tr = $(this);

    // play with $tr
});

有关
的更多信息,请点击此处:

您的代码中几乎没有错误

1.its `timeline` not `#timeline`
2.you can simply refer as tr it should not be $('tr')
除了这个,你的代码是好的

$(“时间线”)。在(“单击”,“tr”,函数(){
警报($(this.attr('data-somedata'));
});

第一排
另一排

$(“#时间线”)。在('click',$('tr')上,函数(事件){
的语法不正确。如果语法正确,
$(此)
将是被单击的tr。将代码更改为
$(“#时间线”)。在('click','tr上,函数(事件)
,则
$(此)
将是
tr更改为“tr”修正了问题,谢谢。这不是一个ID时间线,这是一个元素,所以请删除#在Timline elementBro之前,阅读问题的评论。问题已经修正了。谢谢,你们两个。我很快写了这个问题,没有意识到我把时间线作为一个元素。时间线应该是ID='timeline'@jabeoogie乐意帮忙,可以吗d请编辑您的问题并修复
时间线的
id
,以帮助其他阅读此问题的人?