我的代码中重复了以下 html,并在正确的按钮上添加了“gobutton”类,以便在按下 Enter 时激活:
<div>
<input type="text">
<button id="btnGO" class="gobutton">GO</button>
</div>
还有一段 jquery 代码可以正确触发,但不会激活 gobutton。我猜这是因为最近的函数由于委托(delegate)而无法工作,但我不确定?
$('body').on('keypress', 'input:text', function (e) {
var key = e.which;
if(key == 13) {
e.preventDefault();
$(this).closest('.gobutton').click();
}
});
最佳答案
button
是输入元素的同级元素,而不是父元素,因此 .closest()
当它遍历 DOM 层次结构时将不起作用。
您可以使用.closest()
遍历到公共(public)父级,然后使用 .find()
以定位所需的元素。
使用
$(this).closest('div').find('.gobutton').click();
//$(this).next('.gobutton').click();
//$(this).siblings('.gobutton').click();
您还可以使用.siblings()
或.next()
关于javascript - 在委托(delegate)事件上触发最近的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44545762/