javascript - 在委托(delegate)事件上触发最近的按钮

标签 javascript jquery

我的代码中重复了以下 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/

相关文章:

javascript - 如何获取 x 和 y 值来检测 html5 Canvas 中两个图像之间的碰撞?

jquery - jquery文档准备好的执行顺序

ajax - 循环内的 jQuery.ajax()

javascript - jQuery JSON 对选择器的响应

jQuery:仅当元素存在时如何执行某些操作?

jquery - 如何创建在 jQuery 'on' 对象中的方法之间共享的变量?

javascript - 基于日期选择器设置和获取年龄

javascript - 调用 FB Credits API 时出现错误 1151

javascript - 如何在 THREE.js 中定位纹理图像

javascript - 如何使用 jQuery 或 javaScript 授予用户仅输入 1 到 100 之间的数字的权限