如何在ie8中设置包含函数值的OnClick属性?

edt*_*edt 32 javascript onclick setattribute

我的目标是更改链接的"onclick"属性.我可以成功完成,但结果链接在ie8中不起作用.它确实在ff3中工作.

例如,这适用于firefox3,但不适用于ie8.为什么???

<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>
Run Code Online (Sandbox Code Playgroud)

Hug*_*are 61

您不需要使用setAttribute - 此代码有效(IE8也)

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

  • 在这种情况下,不需要函数或闭包.只是document.getElementById("something").onclick = function(){alert('hello'); }; 没有任何其余的 (5认同)
  • 为什么把它放在封闭中?没理由我能看到. (2认同)

Jon*_*and 9

你最好的选择是使用像jquery或prototype这样的javascript框架,但是,如果失败了,你应该使用:

if (foo.addEventListener) 
    foo.addEventListener('click',doit,false); //everything else    
else if (foo.attachEvent)
    foo.attachEvent('onclick',doit);  //IE only
Run Code Online (Sandbox Code Playgroud)

编辑:

此外,你的功能有点偏.它应该是

var doit = function(){
    alert('hello world!');
}
Run Code Online (Sandbox Code Playgroud)


小智 7

你也可以设置onclick来调用你的函数:

foo.onclick = function() { callYourJSFunction(arg1, arg2); };
Run Code Online (Sandbox Code Playgroud)

这样,您也可以传递参数......