选择 Table 不带 TR 的 TD

Selecting Table TD without TR

我有一个 html Table 这样的:

 <table>
   <tr onClick="someFunc();">
     <td>Foo</td>
     <td><button onClick="anotherFunc();">Bar</button></td>
   </tr>
 </table>

和Javascript:

function somefunc(){
  alert("Foo");
}
function anotherfunc(){
  alert("Bar");
}

问题是当我点击 tr 时工作正常但是当我按下 TD 内的按钮时它会触发这两个功能所以我希望当我点击按钮时只触发按钮功能。

您的 click 操作正在传播到 button 的所有父元素。要停止这种情况,请在 click 事件中使用 event.cancelBubble = true(或者,如果您使用 jQuery,则可以使用 event.stopPropagation())。

首先,不要将内联处理程序与 jQuery 一起使用。这会无缘无故地将处理程序与注册分开,并导致维护问题。使用 类 或 ID 来匹配元素并使用 jQuery 处理程序。

问题是事件传播。要停止点击传播,请在处理程序中使用 e.stopPropagation()

<table>
   <tr class="doSomeFunc">
     <td>Foo</td>
     <td><button class="doAnotherFunc">Bar</button></td>
   </tr>
 </table>

$('.doSomeFunc').click(function(e){
  alert("Foo");
});

$('.doAnotherFunc').click(function(e){
   e.stopPropagation();
   alert("Bar");
});

如果您想坚持使用现有的 非jQuery 代码,只需更改此代码:

<button onClick="anotherFunc();return false;">
来自鼠标处理程序的

return false 将执行与 e.stopPropagation() e.preventDefault().

相同的操作

您需要使用e.stopPropagation();

Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event https://api.jquery.com/event.stoppropagation/

这是一个演示:https://jsfiddle.net/j81czwky/

$("tr").click(function(e){
    alert("Foo");
})

$("button").click(function(e){
   e.stopPropagation();
   alert("Bar");
});


<table>
  <tr>
    <td>Foo</td>
    <td><button>Bar</button></td>
  </tr>
</table>