2017-06-14 95 views
0

我有以下的HTML通过我的代码重复最近的按钮,与正确的按钮“gobutton”类激活进入被按下时:触发对委托事件

<div> 
    <input type="text"> 
    <button id="btnGO" class="gobutton">GO</button> 
</div> 

和jQuery代码块这会正确启动,但不会激活gbutton。我猜这是因为代表团最接近的功能不起作用,但我不确定?

$('body').on('keypress', 'input:text', function (e) { 
    var key = e.which; 
    if(key == 13) { 
     e.preventDefault(); 
     $(this).closest('.gobutton').click(); 
    } 
}); 
+0

'.closest() '在树上搜索。你正在寻找'.siblings()'选择器 – abhishekkannojia

回答

1

button输入元素不是父母的兄弟姐妹,所以.closest()不会因为它穿越了DOM层次的工作。

您可以使用.closest()遍历共同的父亲,然后使用.find()来定位所需的元素。

使用

$(this).closest('div').find('.gobutton').click(); 
//$(this).next('.gobutton').click(); 
//$(this).siblings('.gobutton').click(); 

您还可以使用.siblings().next()

+0

感谢 - 这工作,我已经结束了使用几个函数,但不同的文本字段嵌套在不同类型的容器,并且gobutton并不总是兄弟(有时在较低的SPAN中)。因此,我在表单中为文本字段使用'inp-form'类,在列表项中使用'inp-li'等等。不确定是否有更好的方法可以做到这一点? – user4893295

+0

@ user4893295你可以使用第一种方法,在这里你遍历到共同的父亲,然后定位按钮,即'$(this).closest('div')。find('。gobutton')。click();' – Satpal

+0

尝试过,但由于某种原因,它不适合我。 – user4893295

0

你可以在这里使用一个方法是详细 .next()

例子:$(this).next('.gobutton').click();