我很难找到合适的jQuery选择器来点击某个元素。下面是我拥有的HTML:
<label class="title-label" for="me">Some Title<i class="fa fa-times del-class"></i></label>我有两个独立的jQuery侦听器:
$(document).on("click", ".title-label", function (e) { //magic happens here另外一个是:
$(document).on("click", ".del-class", function (e) { //the whole label gets deleted当我点击标签时,我会向服务器发送.ajax请求,奇迹就会发生。还有一个小的i图标来删除整个标签,这也是有效的。但是,当我单击.del-class图标时,它首先触发对发送请求到服务器的.title-label的单击,魔术发生了,然后标签被删除。图标需要保留在标签内,但当我单击它时,它不应该触发对标签的点击和魔术,而是立即删除标签。
我尝试了各种尝试来包括这样的:not选择器:
:not('.del-class') .title-label但两者都会被触发。知道在这种情况下正确的选择器是什么吗?
发布于 2018-06-15 13:25:23
您可以使用e.stopPropagation()防止事件在DOM树上冒泡,从而防止任何父处理程序被通知该事件。
$(document).on("click", ".title-label", function(e) {
console.log('title-label click');
});
$(document).on("click", ".del-class", function(e) {
e.stopPropagation(); //Add
console.log('del-class click');
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="title-label" for="me">Some Title<i class="fa fa-times del-class"> Other text </i></label>
发布于 2018-06-15 13:27:38
您可以检查event.target是否是图标,并在if/else语句中执行您的操作。
见下文
$(document).on("click", ".title-label", function(e) {
let tgt = e.target
if (!$(tgt).is('.del-class ') ) {
console.log('do magic now')
}
else {
console.log('delete label straight away')
}
//or
!$(tgt).is('.del-class ') ? console.log('do magic now') : console.log('delete label straight away')
})i {
width: 20px;
height: 20px;
background: Red;
display: inline-block;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="title-label" for="me">Some Title<i class="fa fa-times del-class"></i></label>
发布于 2018-06-15 13:33:02
如果我做对了,您有两个元素,其中一个在另一个元素中,如果需要两个单独的侦听器,则需要在子元素上使用event.stopPropagation()。
示例:https://jsfiddle.net/xpvt214o/239539/
$('.parent_div_click').on('click',function(event){
console.log('click in parent');
});
$('.child_i_click').on('click',function(event){
event.stopPropagation();
console.log('click in child');
});希望这能帮上忙
https://stackoverflow.com/questions/50876473
复制相似问题