【问题标题】:Can't get global variables inside the function (javascript)无法在函数内获取全局变量(javascript)
【发布时间】:2015-02-05 13:59:07
【问题描述】:
var selection = document.getElementById('selection');
var closed = true;

function openorclosebar() {

    if(closed == false){
        selection.style.webkitAnimation='bounceOutDown 1s forwards';
        selection.style.animation='bounceOutDown 1s forwards';
        closed = false;
    }
    else{
        selection.style.webkitAnimation='bounceInUp 1s forwards';
        selection.style.animation='bounceInUp 1s forwards';
        closed = true;
    };
}

如何让全局变量“选择”和“关闭”来使用它们。我尝试了“window.selection”和“window.closed”,但没有任何帮助。如果你有想法,请帮助我,这是一个非常重要的项目。

【问题讨论】:

  • openorclosebar 中的代码将成功访问您在函数外部声明的变量。您可能误诊了问题(我希望 selection 不具备您认为应该具备的价值)
  • 我现在能做什么?
  • if (close == false){ close = false } 有什么问题吗?
  • 我已经更正了,但没有任何改变。
  • @SargisAndreyan — 您可以尝试确定您的实际问题是什么,但要查看值是什么,考虑时间并提供更多代码。

标签: javascript variables global


【解决方案1】:

global closed variable 是只读的:它是 windows .closed 属性 - 例如 has happened before with .name :-)

使用 IEFE 将变量设为本地变量:

(function() {
    var selection = document.getElementById('selection');
    var closed = true;

    function openorclosebar() {
        if(!closed) {
            selection.style.webkitAnimation='bounceOutDown 1s forwards';
            selection.style.animation='bounceOutDown 1s forwards';
            closed = false;
        } else {
            selection.style.webkitAnimation='bounceInUp 1s forwards';
            selection.style.animation='bounceInUp 1s forwards';
            closed = true;
        }
    }
}());

还可以在浏览器环境中查看other unsafe names。

【讨论】:

    猜你喜欢
    • 2023-01-29
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 2020-04-04
    • 2019-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多