2013-08-05 50 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