我有一个这样的 html 表格:
<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 内的按钮时它会触发这两个功能所以我想当我点击按钮时只触发按钮功能。
最佳答案
对于初学者,不要将内联处理程序与 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()
.
关于javascript - 选择不带 TR 的表 TD,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29651854/