How to Set OnClick attribute with value containing

2019-03-09 17:27发布

问题:

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 firefox3, 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);