简体   繁体   English

表格行tr中的按钮,当单击按钮时仅执行按钮操作

[英]Button inside table row tr, when clicking button only do button action

I'm trying to have a button inside a row. 我正在尝试在一行中放置一个按钮。

when clicking the button I want it to do A. 单击按钮时,我希望它执行A。

and when clicking the row I want it to do B. 当单击该行时,我希望它执行B。

I tried to stop propagation, and at one point it was working, but I don't know what I didn't and I can't manage to make it work again. 我试图停止传播,但有一次它正在起作用,但是我不知道自己没有做过,而且我无法设法使其再次起作用。

Probably there is a better way to do this. 也许有更好的方法可以做到这一点。

I have a fiddle http://jsfiddle.net/sebababi/YJ6eG/ 我有一个小提琴http://jsfiddle.net/sebababi/YJ6eG/

function stopEvent(ev) {
  ev.stopPropagation();
  alert("event propagation halted.");
}
function stopPropagation(elem) {
  elem = document.getElementById("row1");
  elem.addEventListener("click", stopEvent, true);
}

I changed your code like this: 我这样更改了您的代码:

<table id="ID_to_Stop">
    <tr id="row1" onclick="alert('row 1 clicked');">
        <td id="c12">this is row 1, if you click it, it should do something
            <button id="btn1">and if you click me I should do something different</button>
        </td>
    </tr>
    <tr id="row2" onclick="alert('row 2 clicked');">
        <td id="c22">this is row 2
            <button id="btn2">click me</button>
        </td>
    </tr>
</table>

and the js part: 和js部分:

var btn1 = document.getElementById("btn1");
var btn2 = document.getElementById("btn2");

btn1.addEventListener("click", function (ev) {
    alert('btn 1 clicked');
    ev.stopPropagation();
}, true);

btn2.addEventListener("click", function (ev) {
    alert('btn 2 clicked');
    ev.stopPropagation();
}, true);

And this is your updated DEMO . 这是您更新的DEMO

Your code is not working although.And if it is working in some case, it will allow only single click as you killed the event on row row1 .Use below given code to get desired result. 但是您的代码无法正常工作,如果在某些情况下可以正常工作,则在您杀死行row1上的事件时仅允许单击一下。使用下面的给定代码获得所需的结果。


HTML:- HTML: -


<table id="ID_to_Stop">
<tr id="row1" onclick="alert('row 1 clicked');">
    <td id="c12">this is row 1, if you click it, it should do something
        <button id="btn1" onclick="btn1Call(event);">and if you click me I should do something different</button>
    </td>
</tr>
<tr id="row2" onclick="alert('row 2 clicked');">
    <td id="c22">this is row 2
        <button id="btn2" onclick="btn2Call(event);">click me</button>
    </td>
</tr>


javascript : - javascript:-


<script>

function btn1Call(e) {
    alert('btn 1 clicked');
    e.stopPropagation();
}

function btn2Call(e) {
    alert('btn 2 clicked');
    e.stopPropagation();
}
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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