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

Get javascript variable value from another function

本文关键字:javascript 变量值 获取 函数 另一个      更新时间:2023-09-26

我在第一个 .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');
    }
})
错误:未

捕获引用错误:未定义选中

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

(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 变量,但其他人无法访问该变量。

在函数外部声明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');
    }
})