今天就遇到这个问题,以防其他人遇到同样的问题。
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属性。
execBtn.onclick = function() { runCommand() };
错误提示:
你可以做
execBtn.setAttribute("onclick", function() { runCommand() });
但根据@scunliffe,它将以非标准模式在IE中中断。
你根本做不到
execBtn.setAttribute("onclick", runCommand() );
因为它会立即执行,并将runCommand()的结果设置为onClick属性值,所以您也无法执行
execBtn.setAttribute("onclick", runCommand);
相关分类