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

查看:1352
本文介绍了为什么使用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() };

BAD IDEAS:

你可以做到

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

感谢这篇文章

UPDATE
这是为了证明有时使用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天全站免登陆