javascript 单击行内的按钮时,防止触发表行 onclick 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6491627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:51:35  来源:igfitidea点击:

Prevent table row onclick event to fire when clicking button inside the row

javascripthtmldom

提问by Guy

I have a table row with ONCLICK event (that toggles additional data below). Inside one of the row cells I have a button (when clicked is performing an AJAX action). When I click on the button - the Row's onclick event also fires and what happens is that the additional data appears before the AJAX call completes (which is a bad behavior for me). Any ideas how can I solve this elegantly? (without identifying and coding it into the row's onclick code) Thanks

我有一个带有 ONCLICK 事件的表格行(切换下面的附加数据)。在其中一个行单元格中,我有一个按钮(单击时正在执行 AJAX 操作)。当我单击按钮时 - Row 的 onclick 事件也会触发,并且会在 AJAX 调用完成之前出现附加数据(这对我来说是一种不好的行为)。任何想法如何优雅地解决这个问题?(无需识别并将其编码到行的 onclick 代码中)谢谢

回答by Niklas

Add an event.stopPropagation();to your buttons clickhandler. For more information, have a look hereand here.

event.stopPropagation();向您的按钮click处理程序添加。有关更多信息,请查看此处此处

回答by John

If you dislike the javascript solution, in many cases a CSS solution is possible as well:

如果您不喜欢 javascript 解决方案,在许多情况下,CSS 解决方案也是可能的:

style="pointer-events: none;"

That will supress the <tr>onclick event.

这将抑制<tr>onclick 事件。

However, in some cases I still had issues where it didn't seem to work. In the majority of cases I just use the style above.

但是,在某些情况下,我仍然遇到它似乎不起作用的问题。在大多数情况下,我只使用上面的样式。