从代码段开始:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<body>
<ul>
<li><a class="parentClass" href="#">Parent</a></li>
</ul>
<script>
jQuery(document).ready(function($){
$('.parentClass').append("<span class='childClass'> || Child</span>");
$('.parentClass').click(function(e){
alert('parent');
});
$('.childClass').click(function(e){
//$('.childClass').removeClass('parentClass');
alert('child');
});
});
</script>
</body>
</html>
如果我点击&#34; Parent&#34;我只能查看alert('parent')
,但如果我点击&#34; Child&#34;我不仅会alert('child')
,还会alert('parent')
。
我试图插入$('.childClass').removeClass('parentClass');
,但它不起作用。我无法弄清楚如何避免从子节点启动父节点,而无需修改锚点内的嵌套类...是否可能?
答案 0 :(得分:2)
事件泡沫,你可以停止传播
jQuery(document).ready(function($) {
$('.parentClass').append("<span class='childClass'> || Child</span>");
$('.parentClass').click(function(e) {
alert('parent');
});
$('.childClass').click(function(e) {
e.stopPropagation();
alert('child');
});
});
或确保父母实际上是目标
jQuery(document).ready(function($) {
$('.parentClass').append("<span class='childClass'> || Child</span>");
$('.parentClass').click(function(e) {
if ( this === e.target ) {
alert('parent');
}
});
$('.childClass').click(function() {
alert('child');
});
});
答案 1 :(得分:0)
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<body>
<ul>
<li><a class="parentClass" href="#">Parent</a></li>
</ul>
<script>
jQuery(document).ready(function($){
$('.parentClass').append("<span class='childClass'> || Child</span>");
$('.parentClass').click(function(e){
alert('parent');
});
$('.childClass').click(function(e){
//$('.childClass').removeClass('parentClass');
alert('child');
e.stopPropagation();
});
});
</script>
</body>
</html>
您只需使用.stopPropagation()
答案 2 :(得分:0)
您需要使用event.stopPropagation():
$('.childClass').click(function(e){
e.stopPropagation();
alert('child');
});