Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

javascript - How do you override inline onclick event?

This seems deceptively simple.

How do you override the onclick event in the following HTML using JavaScript?

<a id="sample" href="..." onclick="alert('hello world')" />...</a>

I've tried it with jQuery, but that didn't do the trick:

$('#sample').attr('onclick','alert("done")')

Assume the HTML is pre-written and cannot be changed, other than manipulating it with JavaScript.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this:

// Setting the DOM element's onclick to null removes 
// the inline click handler
$("#sample")[0].onclick = null;
$("#sample").click(function() { alert("done") });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...