我们正在做日志记录,我们有一个网站的标题,我们在点击它时随时记录。元素中的元素也需要记录。有没有一种方法可以仅在使用 jquery .not()
函数或其他任何方法在标题中单击时记录子元素?
HTML
<div id="header">
<div><a class="box blue" href="#">Blue</a></div>
<div><a class="box red" href="#">Red</a></div>
<div><a class="box green" href="#">Green</a></div>
</div>
CSS
$('#header').on('click', function()
alert('header')
});
$('.box').on('click', function() {
alert($(this).attr('class'));
});
最佳答案
您可以使用 jQuery 的 .stopPropagation()
函数来停止从子级到父级的冒泡:
$('#header').on('click', function() {
alert('header');
});
$('.box').on('click', function(e) {
e.stopPropagation();
alert($(this).attr('class'));
});
#header { padding:20px; background:yellow; overflow:auto; }
.box { width:50px; height:50px; float:left; margin:0 20px 0 0; }
.blue { background:blue; }
.red { background:red; }
.green { background:green; }
a { color:white; display:block; text-align:center; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="header">
<div><a class="box blue" href="#">Blue</a></div>
<div><a class="box red" href="#">Red</a></div>
<div><a class="box green" href="#">Green</a></div>
</div>
关于jquery - 选择子元素而不选择父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26062188/