jquery - 将事件侦听器附加到嵌套元素
问题描述
我有一个编辑器,它有一个工具栏,当我突出显示文本时会弹出一个工具栏。当用户单击工具栏上的任何按钮但我的 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")
})
解决方案
如果我们假设它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
。
推荐阅读
- php - 这是一个好习惯吗?– Eloquent:从特定列获取表记录
- windows - Chocolatey 生成的 VS 2015 编译器在 docker 映像上找不到
- python - Discord.py Userinfo 命令错误:在 embed.fields.2.value 中:此字段为必填项
- python - NotFittedError:CountVectorizer - 未安装词汇。在进行情绪分析时
- java - 在列表视图中显示数组的内容
- python-3.x - 从源代码生成选择器,用于scrapy
- c - MSP430 启动板 | 分配双击按钮
- angular - Angular Material 11.0.3 + Tailwind CSS 不起作用
- reactjs - 看课程 react native expo 和 react-native cli
- sql - 在 SQL 查询中条件不为真时跳过联合语句