【问题标题】:JQuery - How to find the id or the row that triggered the action click event?JQuery - 如何找到触发动作点击事件的 id 或行?
【发布时间】:2014-07-04 21:58:10
【问题描述】:

我有 HTML 表格,某些行属于一个类,并且这些行中的每一行都有一个 id。我已使用 jquery 将 onclick 处理程序附加到该类。当单击该类中的任何行时,将触发单击事件。但是事件的源会传播到单击行中的元素。如何获取包含 td(event source) 的行的 id ?

HTML:

<table>
    <tr class="onegroup" id="parent_1">
        <td> Item 1 </td>
        <td> Item 2 </td>
    </tr>
</table>

jquery:

        $(".onegroup").click(function (event) {
          alert(event.target.id); // currently displays undefined as neither of the <td> have an id.
          //Want to display the id of the row ('parent_1')
         });

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

使用 jQuery,您无需去获取 event.target,因为上下文 (this) 已设置为被点击的元素并与选择器匹配。
为了更清楚: 上下文将设置为事件冒泡中出现的第一个元素,该元素适合指定的选择器。

因为 $(this).is('.onegroup') 将始终在您的处理程序函数中返回 true,因为它是您将点击绑定到的选择器。

  $(".onegroup").click(function () {
              alert($(this).attr("id"));
   }); 

【讨论】:

  • 这并不完全正确。 this 将是处理程序绑定到的元素,不一定是触发事件的元素。尽管如此,这正是 OP 想要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多