2012-02-09 26 views
0

我有一個包含另一個div的div。 如果用戶點擊內部div,我只希望附加到這個元素的eventhandler得到執行。現在先是內部元素的事件處理程序,然後執行外部元素的事件處理程序。有沒有辦法改變這個?如果嵌套元素觸發事件,不要讓容器處理它

<html> 
    <head> 
    <meta charset="utf-8"> 
    <title>Demo</title> 
    </head> 
    <body> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script> 
    <script> 
    $(document).ready(function(){ 
     $("#containerElement").click(function(event){ 
     alert("This comes from container"); 
     }); 

     $("#innerElement").click(function(event){ 
     alert("This comes from inner element"); 
     }); 
    }); 
    </script> 


    <div id="containerElement" > 
    This is the container 
    <div id="innerElement" > 
    This is the inner element 


    </div> 

    </div> 
    </body> 
</html> 
+0

太簡單的問題似乎。 2分鐘和4個幾乎完全相同的答案^^ – raphinesse 2012-02-09 22:51:08

回答

2

你可以stop the propagation

$("#innerElement").click(function(event){ 
    alert("This comes from inner element"); 
    event.stopPropagation(); 
}); 
+0

這很好用! – 2012-02-09 23:22:02

0

event.stopPropagation()添加到您的innerElement事件處理函數中。有關更多信息,請參閱jQuery docs

$("#innerElement").click(function(event){ 
    alert("This comes from inner element"); 
    event.stopPropagation(); 
}); 
+0

給予最低代表代表的榮譽! XD – raphinesse 2012-02-09 22:52:50

1

添加event.stopPropagation();

$("#innerElement").click(function(event){ 
    alert("This comes from inner element"); 
    event.stopPropagation(); 
}); 
1

從處理程序返回false將防止起泡(除其他事項外):

$("#innerElement").click(function(event){ 
    alert("This comes from container"); 
    return false; 
}); 
+0

您是否想要將'return false;'添加到'#innerElement'?您的代碼仍然會觸發包含元素的點擊事件。 – 2012-02-09 22:49:46

+0

@科林..感謝 – paislee 2012-02-09 22:50:23