它在Chrome中可以正常工作,但在Firefox中却不能。
这是我的按钮元素:
<button class="btn btn-default">some text <i>remove</i> </button>
这是我的Javascript:
$('button').not('i').click(function(){ alert('button was clicked') });
$('button i').click(function(e){
e.preventDefault();
e.stopPropagation();
alert('i was clicked'); `
});
如何在不触发父级的情况下将单击事件侦听器附加到jQuery中的<i>
标签上?我正在使用引导程序按钮。
在CSS中,我将position: relative;
设置为<button>
,将position: absolute;
设置为<i>
答案 0 :(得分:0)
这就是您想要的,希望这段代码对您有帮助
$("i").click(function(){
alert("I gets clicked ");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn btn-default">some text <i>remove</i> </button>
答案 1 :(得分:0)
仅使用e.stopPropagation();
并尝试
$('button').click(function(){ alert('button was clicked') });
$('button i').click(function(e){
e.stopPropagation();
alert('i was clicked');
})
button{
position:relative;
}
button i{
position:absolute;
left:100px;
top:0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<button class="btn btn-default">some text <i>remove</i> </button>
答案 2 :(得分:0)
尝试一下:
$("i").click(function(){
alert("I gets clicked ");
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<a class="btn btn-default">some text <i>remove</i> </a>
答案 3 :(得分:0)
解决方案是将父级的BUTTON标签替换为其他名称,否则Firefox将无法处理子级的事件侦听器。顺便谢谢答案