我在代码中重复了以下html,在按下回车键时激活的正确按钮上的"gobutton"类:
<div>
<input type="text">
<button id="btnGO" class="gobutton">GO</button>
</div>
以及一个正确触发但不会激活gobutton的jquery代码块。我猜这是因为最近的函数由于委派而无法正常工作,但我不确定?
$('body').on('keypress', 'input:text', function (e) {
var key = e.which;
if(key == 13) {
e.preventDefault();
$(this).closest('.gobutton').click();
}
});
button
是输入元素的同级而不是父元素,因此.closest()
在遍历 DOM 层次结构时不起作用。
可以使用 .closest()
向上遍历到公共父元素,然后使用 .find()
定位所需的元素。
用
$(this).closest('div').find('.gobutton').click();
//$(this).next('.gobutton').click();
//$(this).siblings('.gobutton').click();
您还可以使用.siblings()
或.next()
你可以使用 下一个方法 这里是细节.next((
例 : $(this).next('.gobutton').click();