Howto:在另一个 div 中使用 onclick javascript 的 div [英] Howto: div with onclick inside another div with onclick javascript

查看:19
本文介绍了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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆