2014-09-11 55 views
0

我有一個簡單的代碼。我想單擊按鈕並提醒其ID。該按鈕包含在一個div中。按鈕和div都綁定了一個click()關於點擊()在jquery

問題:如果我點擊按鈕,按鈕的ID會被提醒,然後div的ID也會被提醒。我想阻止div的id被提醒。

代碼

<html> 
<body> 
    <style type="text/CSS"> 
     #mydiv{ 
      border: 1px dashed blue; 
      width: 90px; 
      height: 50px; 
     } 
    </style> 
    <div id="myDiv"> 
     <input type="button" id="myButton" value="Click Me"></input> 
    </div> 

    <script type="text/javascript" src="jquery.js"></script> 
    <script type="text/javascript" src="code.js"></script> 
</body> 
</html> 

Code.js

$('#myDiv').click(function(){ 
      alert($('#myDiv').attr('id')); 
     }); 

$('#myButton').click(function(){ 
      alert($('#myButton').attr('id')); 
     }); 

回答

2

您可以使用事件對象的stopPropagation()方法,以防止它向上bubling。

$('#myButton').click(function(e){ 
    e.stopPropagation(); 
    alert($(this).attr('id')); 
}); 
+0

你是第一個回答? – 2014-09-11 08:18:03

+0

是的,我是... :) – 2014-09-11 08:18:40

+1

我必須等待7分鐘才能接受答案。至少我可以給所有答案+1,他們都是一樣的。 – 2014-09-11 08:19:22

6

您需要使用event.stopPropagation()

冒泡DOM樹,阻止任何父處理程序被通知的事件阻止事件。

如使用

$('#myButton').click(function(event) { 
    event.stopPropagation(); 
    alert(this.id); 
}); 

DEMO

1

使用event.stopPropagation()

$('#myButton').click(function(event){ 
    alert($(this).attr('id')); 
    event.stopPropagation() 
}); 
1
$('#myButton').click(function(e){ // the extra parameter here is the event object 
    e.stopPropagation(); // stops event bubbling up 
    alert($(this).attr('id')); // the this in the current scope is the myButton element so you can just use this.id 
}); 
+0

'prop'會好還是不好? – 2014-09-11 08:22:11

+0

是在某些情況下http://stackoverflow.com/questions/5874652/prop-vs-attr。然而,既然'id'是一個字符串,我會認爲在這種情況下不是?無論如何道具可能會更快,不確定。 – Mardoxx 2014-09-11 08:24:19