【问题标题】:Avoid bubbling in the nested elements避免在嵌套元素中冒泡
【发布时间】:2016-08-11 06:13:44
【问题描述】:

我有这个 html 代码:

<td class="myclass">
    <span>
        <span>xxxx</span>
    </span>
    <span>xxxx</span>
    <span>xxxx</span>
</td>

我将单击事件附加到具有类“myclass”的元素,并将函数作为回调传递。在该函数中,我在 event.target 中收到任何元素,但我想要获取的元素是 td。 ¿ 我可以避免冒泡以便始终获得目标或事件中的 td 吗?

非常感谢

【问题讨论】:

    标签: javascript jquery event-bubbling


    【解决方案1】:

    handler-function 中使用this 上下文

    $('.myclass').on('click', function() {
      console.log(this);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <table>
      <tr>
        <td class="myclass">
          <span>
            <span>xxxx</span>
          </span>
          <span>xxxx</span>
          <span>xxxx</span>
        </td>
      </tr>
    </table>

    或者e.currentTarget

    标识事件的当前目标,因为事件遍历 DOM。它始终引用事件处理程序已附加到的元素,而不是 event.target 标识发生事件的元素。

    $('.myclass').on('click', function(e) {
      console.log(e.currentTarget);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <table>
      <tr>
        <td class="myclass">
          <span>
            <span>xxxx</span>
          </span>
          <span>xxxx</span>
          <span>xxxx</span>
        </td>
      </tr>
    </table>

    【讨论】:

    • 我忘了告诉我不能使用它,因为我需要以这种方式附加事件:$('.myclass').on('click',myFunction);一旦进入我的函数“this”就是文档。
    • @MKP – 第二种方法怎么样?
    • "this" 或 "e.currentTarget" 是回调函数中的文档本身。感谢您的帮助。
    猜你喜欢
    • 2018-09-06
    • 1970-01-01
    • 2016-11-19
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    • 1970-01-01
    • 2014-07-26
    • 1970-01-01
    相关资源
    最近更新 更多