【问题标题】:When using a jQuery delegated event handler, how do I get the descendant selector?使用 jQuery 委托事件处理程序时,如何获取后代选择器?
【发布时间】:2017-01-17 22:28:12
【问题描述】:

使用 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 的解决方案,那也太好了。

【问题讨论】:

  • $("#timeline").on('click', $("tr"), function(event){ 语法不正确。如果语法正确,$(this) 将是被点击的 tr。 api.jquery.com/on
  • 把代码改成$("#timeline").on('click', "tr", function(event),那么$(this)就是tr
  • 将 $("tr") 更改为 "tr" 解决了问题,谢谢。

标签: javascript jquery event-handling jquery-events


【解决方案1】:

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

你将jQuery object传递为selector,你需要将代码更改为以下,那么$(this)将是tr

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

    // play with $tr
});

更多关于on的信息在这里:.on()

【讨论】:

  • 它不是 ID 时间线,它是一个元素,所以在 timliine 元素之前删除 #
  • 兄弟,请阅读问题的 cmets。问题已经解决了。
  • 谢谢你们。我很快写了这个问题,没有意识到我把时间线作为一个元素。 Timeline 应该是一个 id='timeline' 的 div
  • @jabeoogie 很高兴为您提供帮助,您能否编辑您的问题并修复timelineid 以帮助其他阅读此问题的人?
【解决方案2】:

您的代码中几乎没有错误。

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-24
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多