How to Set OnClick attribute with value containing function in ie8?

你离开我真会死。 提交于 2019-12-03 06:23:07

问题


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>

回答1:


You don't need to use setAttribute for that - This code works (IE8 also)

<div id="something" >Hello</div>
<script type="text/javascript" >
    (function() {
        document.getElementById("something").onclick = function() { 
            alert('hello'); 
        };
    })();
</script>



回答2:


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!');
}



回答3:


You could also set onclick to call your function like this:

foo.onclick = function() { callYourJSFunction(arg1, arg2); };

This way, you can pass arguments too. .....




回答4:


You also can use:

element.addEventListener("click", function(){
    // call execute function here...
}, false);


来源:https://stackoverflow.com/questions/1019078/how-to-set-onclick-attribute-with-value-containing-function-in-ie8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!