Howto:div与onclick javascript内的另一个div内的onclick [英] Howto: div with onclick inside another div with onclick javascript

查看:96
本文介绍了Howto:div与onclick javascript内的另一个div内的onclick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是一个简单的问题。我在互相之间使用onclick javascript处理div问题。当我点击内部div时,它应该只会触发它的onclick javascript,但外部div的javascript也被解雇了。如何在不触发外部div的javascript的情况下点击内部div?

 < html> 
< body>
< div onclick =alert('outer'); style =width:300px; height:300px; background-color:green; padding:5px;> outer div
< div onclick =alert('inner');风格=宽度:200像素;高度:200像素;背景颜色:白色; />内部div< / div>
< / div>
< / div>
< / body>
< / html>


解决方案

基本上javascript中有两个事件模型。 事件捕获事件冒泡。在事件冒泡中,如果您点击div内部,则首先触发inside div click事件,然后触发外部div点击。而在事件捕获中,首先触发外部div事件并触发内部div事件。要停止事件传播,请在点击方法中使用此代码。

  if(!e)var e = window.event; 
e.cancelBubble = true;
if(e.stopPropagation)e.stopPropagation();


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>

解决方案

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

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