2017-02-17 25 views
0

以下代碼在firefox中無法正常工作,但它在Chrome中的工作效果非常好。Firefox會忽略子級並在單擊事件時跳到父級

$("#parent").click(function(){ 
 
alert("parent") 
 
}); 
 

 
$("#child").click(function(){ 
 
event.stopPropagation(); 
 
alert("child") 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div style="width:500px;height:500px;background:red;" id="parent"> 
 
<div style="width:200px;height:200px;background:green; font-size:200px" id="child"> 
 
X 
 
</div> 
 
</div>

當我點擊這個孩子,在Firefox中被觸發父的單擊事件,孩子完全被忽略。

我錯過了什麼嗎?

我試圖找到問題,但有關傳播的問題大多存在。

+0

開放開發工具(Firebug)並檢查控制檯中的錯誤信息 – Andreas

回答

2

這是因爲event在Firefox中未定義。 (在其他的瀏覽器,它可能默認爲當前事件。)

爲了解決這個問題,作爲參數添加eventclick功能:

$("#parent").click(function(){ 
 
    alert("parent") 
 
}); 
 

 
$("#child").click(function(event){ 
 
    event.stopPropagation(); 
 
    alert("child") 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div style="width:500px;height:500px;background:red;" id="parent"> 
 
<div style="width:200px;height:200px;background:green; font-size:200px" id="child"> 
 
X 
 
</div> 
 
</div>

+0

嗯所以缺陷是在其他瀏覽器不是Firefox,有趣的事情:) – niceman

+1

也許其他瀏覽器比Firefox更「友善」。 –

0
$("#parent").click(function(e){ 
    if($(e.target).attr('id') == 'child'){ 
    //it's child 
    } else { 
    //its parent 
    } 
}) 
相關問題