I'd like to change the value of the onclick
attribute on an anchor. I want to set it to a new string that contains JavaScript. (That string is provided to the client-side JavaScript code by the server, and it can contains whatever you can put in the onclick
attribute in HTML.) Here are a few things I tried:
- Using jQuery
attr("onclick", js)
doesn't work with both Firefox and IE6/7. - Using
setAttribute("onclick", js)
works with Firefox and IE8, but not IE6/7. - Using
onclick = function() { return eval(js); }
doesn't work because you are not allowed to usereturn
is code passed toeval()
.
Anyone has a suggestion on to set the onclick attribute to to make this work for Firefox and IE 6/7/8? Also see below the code I used to test this.
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var js = "alert('B'); return false;";
// Set with JQuery: doesn't work
$("a").attr("onclick", js);
// Set with setAttribute(): at least works with Firefox
//document.getElementById("anchor").setAttribute("onclick", js);
});
</script>
</head>
<body>
<a href="http://www.google.com/" id="anchor" onclick="alert('A'); return false;">Click</a>
</body>
</html>