繁体   English   中英

Firefox中的JavaScript范围问题

[英]Problems with javascript scope in firefox

<div id="myElement2"></div>

<script>
window.onload = function() {
    document.getElementById("myElement1").onclick = function() {
        for (i = 0; i < 2; i++) {
            document.getElementById("myElement2").onmouseover = func;
            function func() {alert("hello"); } } } }
</script>

在chrome和IE中,当单击myElement1时,func将完美地附加到myElement2。 但是,在firefox中,当单击myElement1时,我收到一条错误消息,指出未定义func。

我应该注意,如果使用匿名函数代替func,那么它可以在所有3种浏览器中使用。

我的问题是,Firefox在这方面与IE和chrome有何不同?

将。

我认为问题在于func正在块内定义。 尝试通过JSLint运行代码,您会注意到以下问题:

  • 函数语句不能放在块中。 使用函数表达式或将语句移到外部函数的顶部。
  • 在定义之前使用了“ func”。

尝试分配一个函数表达式,而不是定义一个函数并按名称分配它,如下所示:

document.getElementById("myElement2").onmouseover = function() {
    alert("hello")
};

至于“ firefox如何在这方面与IE和chrome不同地处理范围?” -参见http://kangax.github.com/nfe/#function-statements

我建议将声明移到赋值的前面,并使用变量来保存函数,而不是全局声明它:

<script>
window.onload = function() {
    document.getElementById("myElement1").onclick = function() {
        for (i = 0; i < 2; i++) {
            var func = function() { alert("hello"); }
            document.getElementById("myElement2").onmouseover = func;
        }
    } 
}
</script>

您有范围问题,因为您的函数定义在函数内。 我通常将函数封装在一个对象中。 您可能也不需要循环。

看一看:

<div id="myElement1"></div>
<div id="myElement2"></div>
<script type="text/javascript">

    window.onload = function() {
        document.getElementById("myElement1").onclick = function() {
                document.getElementById("myElement2").onmouseover = myFunctions.func;
         }
     }
    /* Function definitions */ 
    var myFunctions = new Object();
    myFunctions.func = function () {
       alert("hello"); 
    }
</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM