Javascript 你如何覆盖内联 onclick 事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2629916/
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
How do you override inline onclick event?
提问by Diodeus - James MacFarlane
This seems deceptively simple.
这看似简单。
How do you override the onclick event in the following HTML using JavaScript?
如何使用 JavaScript 覆盖以下 HTML 中的 onclick 事件?
<a id="sample" href="..." onclick="alert('hello world')" />...</a>
I've tried it with jQuery, but that didn't do the trick:
我已经用 jQuery 试过了,但这并没有奏效:
$('#sample').attr('onclick','alert("done")')
Assume the HTML is pre-written and cannot be changed, other than manipulating it with JavaScript.
假设 HTML 是预先编写的,不能更改,只能使用 JavaScript 对其进行操作。
回答by Andrew Hare
Try this:
尝试这个:
// Setting the DOM element's onclick to null removes
// the inline click handler
$("#sample")[0].onclick = null;
$("#sample").click(function() { alert("done") });
回答by supershnee
This can also be done without jQuery:
这也可以在没有 jQuery 的情况下完成:
document.getElementById("sample").setAttribute('onclick','alert("done")');
回答by Ben Everard
<a id="sample" href="..." onclick="alert('hello world'); return false;" />...</a>
Or
或者
$('#sample').attr('onclick','alert("done"); return false;')
Despite being able to set the return false;either directly in the onclick or by using jQuery, it doesn't actually require jQuery to be used at all. The benefit is if for whatever reason your jQuery script leads to a 404, your code will still work.
尽管能够return false;直接在 onclick 中或使用 jQuery 设置 ,但它实际上根本不需要使用 jQuery。好处是,如果您的 jQuery 脚本出于任何原因导致404,您的代码仍然可以工作。
I found the answer here.
我在这里找到了答案。
回答by David Murdoch
Try:
尝试:
document.getElementById("sample").onclick = $.noop;
$.noop == function(){};

