2013-08-05 49 views
1

我做这样的事情怎么办父DIV可点击:有可点击的孩子DIV

<div onclick="foo1()"> 
    <div onclick="foo2()"></div> 
</div> 

当我这样做,我点击子元素,它仍然运行foo1()函数。我如何暂时禁用父元素或什么?

回答

1

我创建了一个工作EXAMPLE

HTML

<div id="parent"> 
    <div id="child"></div> 
</div> 

CSS(只是为了区分两个div)

#parent { 
    background-color: black; 
    width: 220px; 
    height: 220px; 
} 

#child { 
    position:relative; 
    background-color: blue; 
    width: 110px; 
    height: 110px; 
    top:160px; 
    left:160px; 
} 

的JavaScript(包括jQuery的)

$(document).ready(function(){ 
    $('#child').click(function() { 
     alert('Child'); 
     if (!e) var e = window.event; 
     e.cancelBubble = true; 
     if (e.stopPropagation) e.stopPropagation(); 
    }); 
    $('#parent').click(function() { 
     alert('Parent'); 
    }); 
}); 

当你点击的孩子只能从行动孩子正在行动。 您可以根据需要修改我的示例,以实现您所需的功能。

希望这对你有用。

1

是,jQuery的能够解决您的问题。请参见下面的代码:

<script src="jquery.js" type="text/javascript"></script> 
<script> 
function a() 
{ 
    alert('parent'); 
} 

$(document).ready(function(){ 
    $('#div2').click(function(e){alert('child');e.stopPropagation();}) 
}) 
</script> 
<div onclick="a();" style="height:100px;width:100px;border:1px solid red"> 
    <div id="div2" style="height:85px;width:85px;border:1px solid green"> 
    </div> 
</div> 
+0

它不适用于我的情况 –

+0

是否有任何JS错误?检查jquery路径并确保它包含在页面中。 – shairya

0

您可以尝试

<div onclick="foo1(event)"> 
    parent 
    <div onclick="foo2(event)">child</div> 
</div> 

而且

function foo1(e){ 
    console.log('foo1', e) 
} 

function foo2(e){ 
    e.stopPropagation(); 
    console.log('foo2', e) 
} 

演示:Fiddle