首页 > jquery > jQuery变量不会在函数外部发生变化

jQuery变量不会在函数外部发生变化 (jQuery variable doesn't change outside of function)

2013-04-20 jqueryvariables

问题

当按下.sidebar-toggle时,我使用以下代码显示侧边栏,并在按下#page时隐藏侧边栏。

显示侧边栏工作完美,但在按下#page时不会隐藏。单击.sidebar-toggle时,看起来变量未设置为1。

var state = 0;

if (state === 0) {
    $('.sidebar-toggle').click(function() {
        $('#page').animate({marginLeft: '230px'}, 400);
        state = 1;
    });
}

if (state === 1) {
    $('#sidebar').click(function() {
        $('#page').animate({marginLeft: '0'}, 400);
        state = 0;
    });
}

解决方法

你忘了使用#page click.function ...而最好的办法就是将if放在click.function中......尝试这种方式

var state = 0;

$('.sidebar-toggle').click(function() {
    if (state===0) {    
        $('#page').animate({marginLeft: '230px'}, 400);
        state = 1;
    }    
});

$('#page').click(function() {
    if (state===1){
        $('#page').animate({marginLeft: '0'}, 400);
        state = 0;
    }
});

问题

I'm using the following code to show the sidebar when .sidebar-toggle is pressed, and hide the sidebar when #page is pressed.

Showing the sidebar works perfect, but it doesn't hide when #page is being pressed. It looks like the variable isn't set to 1 when the .sidebar-toggle has been clicked.

var state = 0;

if (state === 0) {
    $('.sidebar-toggle').click(function() {
        $('#page').animate({marginLeft: '230px'}, 400);
        state = 1;
    });
}

if (state === 1) {
    $('#sidebar').click(function() {
        $('#page').animate({marginLeft: '0'}, 400);
        state = 0;
    });
}

解决方法

You were forgetting to use the #page click.function ... and the best way is to put the if inside the click.function ... Try this way

var state = 0;

$('.sidebar-toggle').click(function() {
    if (state===0) {    
        $('#page').animate({marginLeft: '230px'}, 400);
        state = 1;
    }    
});

$('#page').click(function() {
    if (state===1){
        $('#page').animate({marginLeft: '0'}, 400);
        state = 0;
    }
});
相似信息