首页 > 解决方案 > 将事件侦听器附加到嵌套元素

问题描述

我有一个编辑器,它有一个工具栏,当我突出显示文本时会弹出一个工具栏。当用户单击工具栏上的任何按钮但我的 jquery 使用变量作为选择器时,我想做一些事情。什么是正确的语法?

HTML:

<div>
  <div class="toolbar">
    <button class="bold"></button>
    <button class="italics"></button>
  </div>
</div>

jQuery:

$('#' + this.editorId > 'toolbar' > button).on("click", (event) => {
  console.log("button on toolbar clicked")
})

标签: jqueryhtml

解决方案


如果我们假设它this.editorId是 的直接祖先.toolbar,即

<div id="toolbar-container">
  <div class="toolbar">
    <button class="bold"></button>
    <button class="italics"></button>
  </div>
</div>

那么,如果this是封闭范围的上下文,例如

function () {
  this.editorId = document.getElementById("#toolbar-container");

  $('#' + this.editorId + ' > .toolbar > button')
      .on("click", (event) => { 
           console.log("button on toolbar clicked") 
      });
}

现在如果.toolbar不是 的直接后代editorId,那么我们可以使用$.find(),我们handler将是:

$('#' + this.editorId + ' .toolbar > button')
      .on("click", (event) => { 
           console.log("button on toolbar clicked") 
      });

我在哪里删除>this.editorId.toolbar


推荐阅读