Howto: div with onclick inside another div with onclick javascript(Howto:在另一个 div 中使用 onclick javascript 的 div)
问题描述
只是一个简单的问题.我在使用 onclick javascript 的 div 中遇到问题.当我单击内部 div 时,它应该只触发它的 onclick javascript,但外部 div 的 javascript 也被触发.用户如何在不触发外部 div 的 javascript 的情况下点击内部 div?
just a quick question. I'm having a problem with divs with onclick javascript within each other. When I click on the inner div it should only fire it's onclick javascript, but the outer div's javascript is also being fired. How can the user click on the inner div without firing the outer div's javascript?
<html>
<body>
<div onclick="alert('outer');" style="width:300px;height:300px;background-color:green;padding:5px;">outer div
<div onclick="alert('inner');" style="width:200px;height:200px;background-color:white;" />inner div</div>
</div>
</div>
</body>
</html>
推荐答案
javascript中基本上有两种事件模型.事件捕获和事件冒泡.在事件冒泡中,如果单击内部 div,则首先触发内部 div 单击事件,然后触发外部 div 单击事件.在事件捕获中,首先触发外部 div 事件,然后触发内部 div 事件.要停止事件传播,请在您的 click 方法中使用此代码.
Basically there are two event models in javascript. Event capturing and Event bubbling. In event bubbling, if you click on inside div, the inside div click event fired first and then the outer div click fired. while in event capturing, first the outer div event fired and than the inner div event fired. To stop event propagation, use this code in your click method.
if (!e) var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
这篇关于Howto:在另一个 div 中使用 onclick javascript 的 div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Howto:在另一个 div 中使用 onclick javascript 的 div


- Flexslider 箭头未正确显示 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01