[英]How to detect the click on a button that is inside of a dropdown with jquery
I am having trouble with a very simple thing.我在一件非常简单的事情上遇到了麻烦。 I have two buttons inside a dropdown, and I can't detect when the user click on them.
我在下拉列表中有两个按钮,当用户点击它们时我无法检测到。 The rest of the buttons works well, less this two.
按键的rest效果不错,少了这两个。
The buttons are:按钮是:
<div class="btn-group">
<button type="button" class="btn btn-secondary btn-sm dropdown-toggle" data-toggle="dropdown">Nodes</button>
<ul class="dropdown-menu" id="NodeFilters">
<button type='button' class='btn btn-secondary btn-sm' id='allFilter'>All</button>
<button type='button' class='btn btn-secondary btn-sm' id='cleanFilter'>Clean</button>
</ul>
</div>
My function is:我的 function 是:
//This function controls if some button is clicked
function btnController(){
$('.btn').click(function(){
let id_btn = $(this).attr("id");
console.log(id_btn);
if(id_btn == 'allFilter' | id_btn == 'cleanFilter'){
alert('sss')
}
});
}
$(document).ready(function() {
btnController();
} );
When I click the rest of the buttons, the console.log(id_btn);
当我单击按钮的 rest 时,
console.log(id_btn);
prints the id
of the button.打印按钮的
id
。 But when I click these two buttons inside the dropdown, nothing happens.但是当我单击下拉列表中的这两个按钮时,什么也没有发生。 Why is this happening?
为什么会这样?
Note: When I click these buttons, the dropdown always gets closed.注意:当我单击这些按钮时,下拉菜单总是关闭。
Can somebody help me?有人可以帮助我吗? Thank you very much!
非常感谢!
Use event delegation like this:像这样使用事件委托:
$(function(){
$(document).on('click', '.btn', function(){
let id_btn = $(this).attr("id");
console.log(id_btn);
if(id_btn === 'allFilter' || id_btn === 'cleanFilter'){
alert('sss')
}
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.