【问题标题】:Differences in browser scope treatment of chrome/firefoxchrome/firefox浏览器作用域处理的差异
【发布时间】:2013-02-16 13:40:03
【问题描述】:

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

var x="hi.", b;
(b = document.createElement("button")).innerHTML = "click me";
b.setAttribute("onclick", "alert(x)"); // Doesn't work on FF, but works on Chrome
document.body.appendChild(b);

当我使用 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);

导致这种情况的两种浏览器有什么区别?

【问题讨论】:

    标签: javascript google-chrome dom cross-browser scope


    【解决方案1】:

    这应该在 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。

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

    【讨论】:

    • @Teemu - 嗯,你仍然需要传递变量,如果它在 Chrome 中像现在这样工作,那一定是因为 x 在某种程度上是全局的还是其他一些侥幸?当我在 Chrome 中尝试 OP 的代码时,我在控制台中得到“x 未定义”。
    • 好吧,我的 FF、IE9 和 10、Chrome 和 Opera 都发出了“嗨”的警报。当运行你的小提琴时......
    • @Teemu - 真好。我只是似乎记得你不能在 IE 中使用 setAttribute 设置像 onclick 这样的内联事件,但如果它有效,我想你可以,至少在较新的版本中。
    • @Teemu - 我实际上需要传递变量,因为它在执行期间会发生变化。
    • @Macmod 您注意到代码之间的细微差别了吗?你有b.setAttribute("onclick", "alert(x)");,而adeno 有b.setAttribute("onclick", "alert('"+x+"')");,这将解决所有(现代)浏览器中的问题。
    猜你喜欢
    • 2015-10-11
    • 2017-03-08
    • 2016-11-01
    • 1970-01-01
    • 2011-07-31
    • 1970-01-01
    • 2022-01-16
    • 2021-04-07
    • 2020-03-20
    相关资源
    最近更新 更多