今天遇到这个问题,发帖以防其他人遇到同样的问题。
var execBtn = document.createElement('input');
execBtn.setAttribute("type", "button");
execBtn.setAttribute("id", "execBtn");
execBtn.setAttribute("value", "Execute");
execBtn.setAttribute("onclick", "runCommand();");
原来要让 IE 在动态生成的元素上运行 onclick,我们不能使用 setAttribute。相反,我们需要使用包装我们要运行的代码的匿名函数来设置对象的 onclick 属性。
execBtn.onclick = function() { runCommand() };
坏主意:
你可以做到
execBtn.setAttribute("onclick", function() { runCommand() });
但根据@scunliffe,它会在非标准模式下在 IE 中中断。
你根本不能这样做
execBtn.setAttribute("onclick", runCommand() );
因为是立即执行,并且把runCommand()的结果设置为onClick属性值,你也做不到
execBtn.setAttribute("onclick", runCommand);
最佳答案
为了使它在 FF 和 IE 中都能工作,你必须用两种方式编写:
button_element.setAttribute('onclick','doSomething();'); // for FF
button_element.onclick = function() {doSomething();}; // for IE
感谢this post .
更新: 这是为了说明有时候有必要使用setAttribute!如果您需要从 HTML 中获取原始的 onclick 属性并将其添加到 onclick 事件,这样它就不会被覆盖,则此方法有效:
// get old onclick attribute
var onclick = button_element.getAttribute("onclick");
// if onclick is not a function, it's not IE7, so use setAttribute
if(typeof(onclick) != "function") {
button_element.setAttribute('onclick','doSomething();' + onclick); // for FF,IE8,Chrome
// if onclick is a function, use the IE7 method and call onclick() in the anonymous function
} else {
button_element.onclick = function() {
doSomething();
onclick();
}; // for IE7
}
关于javascript - 为什么使用 setAttribute 设置的 onclick 属性在 IE 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/95731/