[英]click event box inside box in html
I have code: 我有代码:
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>
When I click Box B, I just want to show "B" not "AB". 单击框B时,我只想显示“ B”而不是“ AB”。 Any ideas?
有任何想法吗?
Use event.stopPropagation()
which stops the click event from bubbling to parent element like the following: 使用
event.stopPropagation()
可以将click事件停止冒泡为父元素,如下所示:
var box = document.querySelectorAll("div"); box.forEach(function(element) { element.onclick = function(event) { event.stopPropagation(); alert(this.innerText); } });
<div style="height: 500px; width: 500px; background: red"> A <div style="height: 200px; width: 200px; background: blue;"> B </div> </div>
1.solution: You could cancel all other events using event.stopPropagation();
1.解决方案:您可以使用
event.stopPropagation();
取消所有其他事件event.stopPropagation();
Have a look at the jQuery docs . 看一下jQuery文档 。
event.stopPropagation-Description : Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
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); } });
<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>
2. solution: You could of course also use the method to separate the two div elements like this: 2.解决方案:当然,您也可以使用该方法将两个div元素分开,如下所示:
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> <div style="height: 200px; width: 200px; background: blue;"> B </div>
I think this is your need. 我认为这是您的需要。
function a(div) { alert(div.innerHTML); }
<div style="height: 500px; width: 500px; background: red">A <div style="height: 200px; width: 200px; background: blue;" onclick="a(this);">B</div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.