IE setAttribute onclick 问题

本文探讨了在使用JavaScript动态创建HTML元素时,如何在IE浏览器中正确设置`onclick`属性以触发事件。通过使用匿名函数包裹目标函数来避免IE的兼容性问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值