2014-09-11 54 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