最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to make disable onclick element of parent element - Stack Overflow

programmeradmin6浏览0评论

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?

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?

Share Improve this question edited May 25, 2019 at 13:55 halfer 20.4k19 gold badges109 silver badges202 bronze badges asked Jan 12, 2011 at 6:41 RajasekarRajasekar 19k35 gold badges109 silver badges140 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

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>
发布评论

评论列表(0)

  1. 暂无评论