簡體   English   中英

如何禁用父元素的onclick元素

[英]How to make disable onclick element of parent element

我有一張桌子,上面有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>

如何實現呢?

您需要停止事件冒泡

注意

使其不顯眼

<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();
    });
});
<td><button onclick="doprocess2(event);"</td>

 function doprocess2(evt) {

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

    // your existing code goes here
}

這適用於Firefox,Chrome和IE9。 不確定IE的舊版本不會傳遞“事件”對象。 (改為使用window.event)。

有幾種方法可以做到這一點。 就您而言,最簡單的方法可能是:

像這樣定義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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM