从另一个函数获取javascript变量值

时间:2016-02-20 23:59:38

标签: javascript jquery

我在第一个 .click 函数中声明了一个变量,但是在我的第二个 .click 中,我试图获取第一个变量值,但它不是能够找到它,因为它处于不同的功能。

如何设置全局变量或其他函数也可以使用该值的东西?

$('input[type="checkbox"]').click(function(){
    var checked = 0;
    if($(this).prop("checked") == true){
        var checked = 1
        console.log('checked');
        console.log(checked);
    }
    else if($(this).prop("checked") == false){
        var checked = 0
        console.log('not checked');
        console.log(checked);
    }
});
$('#button-cart').click(function(){
    if(checked == 1){
        alert('can continue fine');
    } else if(checked == 0){
        alert('cannot continue');
    }
})

错误:未捕获的ReferenceError:未定义检查

2 个答案:

答案 0 :(得分:3)

为避免污染全局范围,最佳做法是在闭包中声明checked变量,以便只有您的事件处理程序才能访问它。

(function() {
    var checked; // No one outside of this immediately invoked function can see the checked variable.
    $('input[type="checkbox"]').click(function(){
        checked = 0;
        if($(this).prop("checked") == true){
            checked = 1
            console.log('checked');
            console.log(checked);
        }
        else if($(this).prop("checked") == false){
            checked = 0
            console.log('not checked');
            console.log(checked);
        }
    });
    $('#button-cart').click(function(){
        if(checked == 1){
            alert('can continue fine');
        } else if(checked == 0){
            alert('cannot continue');
        }
    })
}());

这样,您的点击处理程序都可以看到checked变量,但其他任何人都无法访问它。

答案 1 :(得分:2)

在函数外部声明checked - 这使得它可以在全局范围内访问。然后删除函数内的var语句,或者在函数范围内创建一个新变量。这段代码可以使用:

var checked = 0;
$('input[type="checkbox"]').click(function(){
    if($(this).prop("checked") == true){
        checked = 1
        console.log('checked');
        console.log(checked);
    }
    else if($(this).prop("checked") == false){
        checked = 0
        console.log('not checked');
        console.log(checked);
    }
});
$('#button-cart').click(function(){
    if(checked == 1){
        alert('can continue fine');
    } else if(checked == 0){
        alert('cannot continue');
    }
})