我有代码:
var box = document.querySelectorAll("div");
box.forEach(function(element) {
element.onclick = function() {
alert(this.innerText);
}
});

<div style="height: 500px; width: 500px; background: red">
A
<div style="height: 200px; width: 200px; background: blue;">
B
</div>
</div>
&#13;
当我点击方框B时,我只想显示&#34; B&#34;不是&#34; AB&#34;。有什么想法吗?
答案 0 :(得分:1)
使用event.stopPropagation()
来阻止点击事件冒泡到父元素,如下所示:
var box = document.querySelectorAll("div");
box.forEach(function(element) {
element.onclick = function(event) {
event.stopPropagation();
alert(this.innerText);
}
});
&#13;
<div style="height: 500px; width: 500px; background: red">
A
<div style="height: 200px; width: 200px; background: blue;">
B
</div>
</div>
&#13;
答案 1 :(得分:0)
1.solution:您可以使用event.stopPropagation();
取消所有其他活动。查看jQuery docs。
event.stopPropagation-Description :Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
var box = document.querySelectorAll("div");
box.forEach(function(element) {
element.onclick = function(event) {
event.stopPropagation();
alert(this.innerText);
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="height: 500px; width: 500px; background: red">
A
<div style="height: 200px; width: 200px; background: blue;">
B
</div>
</div>
&#13;
<强> 2。解决方案:您当然也可以使用该方法来分隔两个div元素,如下所示:
var box = document.querySelectorAll("div");
box.forEach(function(element) {
element.onclick = function() {
alert(this.innerText);
}
});
&#13;
<div style="height: 500px; width: 500px; background: red">
A
</div>
<div style="height: 200px; width: 200px; background: blue;">
B
</div>
&#13;
答案 2 :(得分:0)
我认为这是你的需要。
function a(div) {
alert(div.innerHTML);
}
&#13;
<div style="height: 500px; width: 500px; background: red">A
<div style="height: 200px; width: 200px; background: blue;" onclick="a(this);">B</div>
</div>
&#13;