javascript - 为什么使用 setAttribute 设置的 onclick 属性在 IE 中不起作用?

标签 javascript internet-explorer

今天遇到这个问题,发帖以防其他人遇到同样的问题。

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/

相关文章:

javascript - Jquery验证器模块和成功后的函数调用

javascript - D3 : Constrained Semantic Zooming on a Tree Layout

javascript - Angular 可以激活无限调用

internet-explorer - 直接将 JPEG 嵌入 HTML 文件中

javascript - 如何在 JavaScript 中制作 IE 插件/扩展?

c# - 删除 -noframemerging 选项的正确方法

javascript - 如何在 ASP.Net 中的一个控件的两个 CSS 类之间切换?

javascript - 对象存在,但在 YouTube 响应中仍未定义?

java - 对象不支持该属性或方法--在IE9中调用Applet

html - 为什么IE11选择渲染模式: "IE7 Strict" and how to i make it use current browser?