可点击表格单元格内的按钮

5
我有一个可点击的表格单元格,当它被点击时会触发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>

当按钮被点击时,如何防止单元格点击事件被触发?
4个回答

6
你可以使用stopPropagation()函数,它可以阻止事件冒泡到父元素。 示例
$('#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>

谢谢Dipesh。所有的答案都很好,但我选择这个因为它更完整。 - Citrus

2

停止事件冒泡,即阻止向父元素冒泡传递的事件:

$('#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();
      }    
   });    
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接