My goal is to change the onclick
attribute of a link. I can do it successfully, but the resulting link doesn't work in ie8. It does work in ff3.
For example, this works in Firefox 3, but not IE8. Why?
<p><a id="bar" href="#" onclick="temp()">click me</a></p>
<script>
doIt = function() {
alert('hello world!');
}
foo = document.getElementById("bar");
foo.setAttribute("onclick","javascript:doIt();");
</script>
This question is related to
javascript
onclick
setattribute
You also can use:
element.addEventListener("click", function(){
// call execute function here...
}, false);
You could also set onclick to call your function like this:
foo.onclick = function() { callYourJSFunction(arg1, arg2); };
This way, you can pass arguments too. .....
your best bet is to use a javascript framework like jquery or prototype, but, failing that, you should use:
if (foo.addEventListener)
foo.addEventListener('click',doit,false); //everything else
else if (foo.attachEvent)
foo.attachEvent('onclick',doit); //IE only
edit:
also, your function is a little off. it should be
var doit = function(){
alert('hello world!');
}
Source: Stackoverflow.com