如何禁用父元素的onclick子元素

4
我有一个包含tr的表格,如下所示:
<tr onclick="doprocess1()">
   <td>Some data</td>
   <td>Some data</td>
   <td><button onclick="doprocess2()"</td>  <!--I want to disable the clickevent of the <tr> here -->
</tr>

如何实现这个目标?
3个回答

3

你需要停止事件冒泡

注意:

使其不显眼

<tr id="tr1">
   <td>Some data</td>
   <td>Some data</td>
   <td><button id="bt1">Click</button></td>  <!--I want to disable the clickevent of the <tr> here -->
</tr>


$(function(){
    $("#tr1").click(function(){
    });
    $("#bt1").click(function(e){
        e.stopPropagation();
    });
});

2
<td><button onclick="doprocess2(event);"</td>

 function doprocess2(evt) {

    evt.stopPropagation();
    evt.preventDefault();

    // your existing code goes here
}

这在Firefox、Chrome和IE9上都有效。不确定在旧版本的IE上是否有效,因为“event”对象没有被传递。(请使用window.event代替)。


2
有几种方法可以实现这个目标。在你的情况下,最简单的方法可能是以下方式:
将 doprocess2 定义为下面这样:
function doprocess2(e) {
    e.stopPropagation && e.stopPropagation() || (e.cancelBubble = true);
    ...
}

然后可以像这样调用它:

onclick="doprocess2(event);"

这将适用于所有现代浏览器,包括ie6、ie7和ie8。

以下是一个可行的示例:

<html>
<head>
<script>
function doprocess1() { alert('tr'); }
function doprocess2(e) {
    e.stopPropagation && e.stopPropagation() || (e.cancelBubble = true);
    alert('td');
}
</script>
</head>
<body>
<table>
<tr onclick="doprocess1();">
    <td>click tr</td>
    <td><button onclick="doprocess2(event);">click td only</button></td>
</tr>
</table>
</body>
</html>

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