简体   繁体   中英

How to make disable onclick element of parent element

I had a table with tr's like

<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>

How to achieve this?

You need to stop event bubbling .

Note

Make it unobtrusive

<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
}

This works on Firefox, Chrome, and IE9. Not sure about older versions of IE where the "event" object doesn't get passed. (Use window.event instead).

There are several ways to do this. In your case the easiest is probably the following:

define doprocess2 like this:

function doprocess2(e) {
    e.stopPropagation && e.stopPropagation() || (e.cancelBubble = true);
    ...
}

and call it like this:

onclick="doprocess2(event);"

This will work in all modern browsers and also ie6, ie7 & ie8

Here is a workable example:

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM