当前位置: 代码迷 >> Web前端 >> IE setAttribute onclick 有关问题
  详细解决方案

IE setAttribute onclick 有关问题

热度:946   发布时间:2012-11-23 22:54:33.0
IE setAttribute onclick 问题

Why does an onclick property set with setAttribute fail to work in 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();");
?

?

?

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:

You can do

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

?

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

?

You can't do this at all

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

?

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

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

?

?

?

?


Or you could use jQuery and avoid all those issues:

var execBtn = $("<input>")
    .attr("type", "button")
    .attr("id", "execBtn")
    .attr("value", "Execute")
    .click(runCommand);
?

jQuery will take care of all the cross-browser issues as well.

?


  相关解决方案