JavaScript: changing the value of onclick with or without jQuery
You shouldn't be using onClick
any more if you are using jQuery. jQuery provides its own methods of attaching and binding events. See .click()
$(document).ready(function(){
var js = "alert('B:' + this.id); return false;";
// create a function from the "js" string
var newclick = new Function(js);
// clears onclick then sets click using jQuery
$("#anchor").attr('onclick', '').click(newclick);
});
That should cancel the onClick
function - and keep your "javascript from a string" as well.
The best thing to do would be to remove the onclick=""
from the <a>
element in the HTML code and switch to using the Unobtrusive method of binding an event to click.
You also said:
Using
onclick = function() { return eval(js); }
doesn't work because you are not allowed to use return in code passed to eval().
No - it won't, but onclick = eval("(function(){"+js+"})");
will wrap the 'js' variable in a function enclosure. onclick = new Function(js);
works as well and is a little cleaner to read. (note the capital F) -- see documentation on Function()
constructors
BTW, without JQuery this could also be done, but obviously it's pretty ugly as it only considers IE/non-IE:
if(isie)
tmpobject.setAttribute('onclick',(new Function(tmp.nextSibling.getAttributeNode('onclick').value)));
else
$(tmpobject).attr('onclick',tmp.nextSibling.attributes[0].value); //this even supposes index
Anyway, just so that people have an overall idea of what can be done, as I'm sure many have stumbled upon this annoyance.