无法在函数内部获取全局变量(javascript)

时间:2015-02-05 13:59:07

标签: javascript variables global

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”,但没有任何帮助。如果您有任何想法,请帮助我,这是非常重要的项目。

1 个答案:

答案 0 :(得分:0)

global closed variable是只读的:它是window s .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