为什么使用 setAttribute 设置的 onclick 属性无法在 IE 中工作? [英] Why does an onclick property set with setAttribute fail to work in IE?

查看:20
本文介绍了为什么使用 setAttribute 设置的 onclick 属性无法在 IE 中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Ran into this problem today, posting in case someone else has the same issue.

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 属性,该函数封装了我们要运行的代码.

Turns out to get IE to run an onclick on a dynamically generated element, we can't use setAttribute. Instead, we need to set the onclick property on the object with an anonymous function wrapping the code we want to run.

execBtn.onclick = function() { runCommand() };

糟糕的想法:

你可以这样做

execBtn.setAttribute("onclick", function() { runCommand() });

但根据@scunliffe 的说法,它会在非标准模式下在 IE 中崩溃.

but it will break in IE in non-standards mode according to @scunliffe.

你根本不能这样做

execBtn.setAttribute("onclick", runCommand() ); 

因为它立即执行,并将runCommand()的结果设置为onClick属性值,你也做不到

because it executes immediately, and sets the result of runCommand() to be the onClick attribute value, nor can you do

execBtn.setAttribute("onclick", runCommand);

推荐答案

要在 FF 和 IE 中都能正常工作,您必须同时编写:

to make this work in both FF and IE you must write both ways:


    button_element.setAttribute('onclick','doSomething();'); // for FF
    button_element.onclick = function() {doSomething();}; // for IE

感谢这篇文章.

更新:这是为了证明有时需要使用 setAttribute!如果您需要从 HTML 中获取原始 onclick 属性并将其添加到 onclick 事件中,则此方法有效,以便它不会被覆盖:

UPDATE: This is to demonstrate that sometimes it is necessary to use setAttribute! This method works if you need to take the original onclick attribute from the HTML and add it to the onclick event, so that it doesn't get overridden:

// 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
}

这篇关于为什么使用 setAttribute 设置的 onclick 属性无法在 IE 中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆