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
基础教程推荐
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
