2013-03-04 96 views
4

我有一个表格单元格,它可点击并点击时触发jQuery事件。在这个单元格中,我也有一个按钮,当点击时有另一个jQuery事件。问题是,单击按钮时,单元格和按钮事件都会被触发。点击表格单元格内的按钮

例如:

<script> 
    $(document).ready(function() { 
     $('#cell').click(function() { 
      alert('cell clicked'); 
     });   
     $('#button').click(function() { 
      alert('button clicked'); 
     }); 
    }); 
</script> 

<table> 
    <tr> 
     <td id="cell"> 
      <button id="button">go</button> 
     </td> 
    </tr> 
</table> 

我怎样才能防止电池点击事件单击按钮时被解雇?

回答

6

您可以使用stopPropagation(),它允许您停止将事件冒泡到父dom。

$('#button').click(function (e) { 
    e.stopPropagation(); 
    alert('button clicked'); 
}); 

table宽度设定为100%并进行测试。

测试代码

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

    $(function() 
    { 
     $('#cell').click(function() { 
      alert('cell clicked'); 
     });   
     $('#button').click(function (e) { 
      e.stopPropagation(); 
      alert('button clicked'); 
     }); 
    }); 

</script> 
<table width="100%"> 
    <tr> 
     <td id="cell"> 
      <button id="button">go</button> 
     </td> 
    </tr> 
</table> 
+0

谢谢Dipesh。所有好的答案,但采摘完整性。 – 2013-03-04 11:26:07

+1

@deen随时欢迎兄弟... – 2013-03-04 11:26:42

2

停止event propagation被称为event bubbling to the parent

$('#button').click(function (e) { 
     e.stopPropagation(); 
     alert('button clicked'); 
    }); 
2

您需要使用

stopPropagation 

这个例子应该修复它:

$(document).ready(function() { 
    $('#cell').click(function() { 
     alert('cell clicked'); 
    });   
    $('#button').click(function (e) { 
     e.stopPropagation(); 
     alert('button clicked'); 
    }); 
}); 

这应该解决它。

2
$(document).ready(function(){ 
    $('#cell').click(function(event){ 
    if($(event.target).is('#button')){ 
     event.stopPropagation(); 
     }  
    });  
}); 
相关问题