这看起来似乎很简单。
如何使用JavaScript覆盖以下HTML中的onclick事件?
<a id="sample" href="..." onclick="alert('hello world')" />...</a>
我已经尝试使用jQuery,但那并没有成功:
$('#sample').attr('onclick','alert("done")')
假设HTML已经预先编写好且不能更改,除了可以使用JavaScript进行操作。
这看起来似乎很简单。
如何使用JavaScript覆盖以下HTML中的onclick事件?
<a id="sample" href="..." onclick="alert('hello world')" />...</a>
我已经尝试使用jQuery,但那并没有成功:
$('#sample').attr('onclick','alert("done")')
假设HTML已经预先编写好且不能更改,除了可以使用JavaScript进行操作。
试一下这个:
// Setting the DOM element's onclick to null removes
// the inline click handler
$("#sample")[0].onclick = null;
$("#sample").click(function() { alert("done") });
这也可以在没有jQuery的情况下完成:
document.getElementById("sample").setAttribute('onclick','alert("done")');
<a id="sample" href="..." onclick="alert('hello world'); return false;" />...</a>
或者
$('#sample').attr('onclick','alert("done"); return false;')
return false;
,也可以使用jQuery进行设置,但实际上并不需要使用jQuery。好处是,如果由于某种原因您的jQuery脚本导致404
错误,您的代码仍将正常工作。尝试:
document.getElementById("sample").onclick = $.noop;
$.noop == function(){};
的汉语翻译是:{{链接1:jQuery noop}}
。$("#sample")[0].onclick = null;
和 document.getElementById("sample").onclick = $.noop;
几乎相同。你怎么能说这没有起作用? - David Murdoch
[0]
将获取选择器的第一个匹配元素。 - Andy Eonclick
事件:$('.datacell').each(function() {this.onclick = $.noop;});
,这与我的情况类似。请注意,翻译内容不包括解释和额外信息。 - bPratik