首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

IE setAttribute onclick 有关问题

2012-11-23 
IE setAttribute onclick 问题Why does an onclick property set with setAttribute fail to work in IE??

IE setAttribute onclick 问题
Why does an onclick property set with setAttribute fail to work in IE?

?

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() });
?

?

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

?

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

?

?

?

?


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.

?


热点排行