如果我有一个 <div class="timely"></div>
包含一个表,该表中有一个 <th class="prev"><i>previous</i></th>
...Chrome 开发工具表示 <th>
上有一个事件监听器,但 Firefox 开发工具指出它不在 <th>
上,但是父级 .timely
,Chrome 在查看此事件的处理程序中的内容时也会指出这一点。
我想做的是复制点击时发生的情况,以及按键时发生的情况。它看起来并不像 jQuery 中那么简单:
$('.timely th').each(function(){
$(this).on('keyup', function(){
$(this).trigger('click');
});
});
因为事件处理程序位于 .timely
并且它在执行代码时从事件冒泡的地方监听。
如何复制.timely
的keyup上的点击事件它的上下文从<th>
冒泡?
最佳答案
首先,请注意您的 each
没有理由循环(除非您在其中执行其他未显示的操作)。请记住,jQuery 是基于集合的,因此 $("selector").on(...)
在集合中的所有元素上设置处理程序。
回复您的问题:接受事件参数并使用其 target
属性作为要触发的元素:
$('.timely th').on('keyup', function(e) {
$(e.target).trigger('click');
});
或者如果您想在 .timely
上处理它而不是 th
在.timely
,只需更改选择器并使用委托(delegate)形式(假设您只需要 th
元素):
$('.timely').on('keyup', 'th', function(e) {
$(e.target).trigger('click');
});
获取 keyup
很困难在th
上当然是元素;立即想到的唯一方法是输入 input
th
中的元素所以keyup
气泡:
$('.timely th').on('keyup', function(e) {
console.log("keyup");
$(e.target).trigger('click');
});
$('.timely th').on('click', function(e) {
console.log('click');
});
<div class="timely">
<table>
<tbody>
<tr>
<th>
<input type="text">
</th>
</tr>
</tbody>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
您还没有说出您想要触发的原因 click
上keyup
,但如果只是运行 click
事件处理程序,我不建议这样做。相反,只需对keyup
使用相同的函数即可。和click
处理程序。您只需在 .on
中通过空格分隔即可 Hook 多个事件。 ( .on("click keyup", ...)
),或者使用命名函数并在连接 click
的位置引用它和keyup
处理程序。
Chrome dev tools say there is an event listener on the
<th>
, but Firefox dev tools points out it is not on the<th>
, but the parent.timely
如果您不想看到附加到祖先的处理程序,请取消选中“事件监听器”选项卡中的祖先框:
但请注意,在您的示例代码中,处理程序肯定位于 th
上,不是祖先.timely
元素。
关于javascript - 父级触发事件,从子级冒泡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45694696/