Javascript chrome/firefox浏览器范围处理的差异

Javascript chrome/firefox浏览器范围处理的差异,javascript,google-chrome,dom,cross-browser,scope,Javascript,Google Chrome,Dom,Cross Browser,Scope,这会在chrome中提醒x,但在firefox(chrome 25.0/FF 11.0)上不会: 当我使用DOM(b.onclick,如下面的代码)时,它可以在这两种情况下工作,但当使用字符串形式的属性时,它返回“x not defined”错误,如上面的代码 var x="hi.", b; (b = document.createElement("button")).innerHTML = "click me"; b.onclick = function(){alert(x)}; // Wor

这会在chrome中提醒x,但在firefox(chrome 25.0/FF 11.0)上不会:

当我使用DOM(b.onclick,如下面的代码)时,它可以在这两种情况下工作,但当使用字符串形式的属性时,它返回“x not defined”错误,如上面的代码

var x="hi.", b;
(b = document.createElement("button")).innerHTML = "click me";
b.onclick = function(){alert(x)}; // Works on FF/Chrome
document.body.appendChild(b);

这两种浏览器之间的差异是什么导致的?

这应该在FF和Chrome中工作,但在IE中不工作,您需要实际传递变量

var x="hi.", b;
(b = document.createElement("button")).innerHTML = "click me";
b.setAttribute("onclick", "alert('"+x+"')");
document.body.appendChild(b);
据我所知,在(旧版本的)IE中,无法使用setAttribute设置内联javascript


(在FF 19和最新的Chrome中测试)

@Teemu-Uhm,您仍然需要传递变量,如果它在Chrome中像现在这样工作,那一定是因为
x
是全局的还是其他的侥幸?当我在Chrome中尝试OP的代码时,我在控制台中得到了“x未定义”。我的FF、IE9和10、Chrome和Opera都发出了“嗨”的警报。当运行你的小提琴时…@Teemu-太好了。我似乎记得你不能在IE中设置像onclick with setAttribute这样的内联事件,但如果它有效,我想你可以,至少在较新的版本中。@Teemu-我实际上需要传递变量,因为它在执行过程中会发生变化。@Macmod你注意到代码之间的一点差异了吗?您有
b.setAttribute(“onclick”、“alert(x)”和adeneo具有
b.setAttribute(“onclick”、“alert(““+x+”)”),这将解决所有(现代)浏览器中的问题。
var x="hi.", b;
(b = document.createElement("button")).innerHTML = "click me";
b.setAttribute("onclick", "alert('"+x+"')");
document.body.appendChild(b);