【问题标题】:Using Local variable value's in Jquery在 Jquery 中使用局部变量值
【发布时间】:2014-10-30 06:58:59
【问题描述】:

我的脚本中有这个功能:

(document).ready(function () {
$(".plcardFirst").change(function() {
valueFirst = $( ".plcardFirst" ).val();
        });
$(".plcardSecond").change(function() {
valueSecond = $( ".plcardSecond" ).val();
    });
});

如何使用 valueFirstvalueSecond 值来计算和运行 if 语句? 非常感谢

【问题讨论】:

    标签: jquery variables global local var


    【解决方案1】:

    注意 javascript函数作用域非块作用域,这意味着在函数内使用关键字 var 声明的变量strong> 只能在该函数内部使用。 但是在这里您声明 valueFirstvalueSecond 没有 关键字 var,因此它们都被视为 全局变量,因此您可以访问即使在 if 语句中,您也可以随时随地使用它们

    你也可以这样使用:

    $(document).ready(function () {
    var valueFirst,valueSecond; // declaring both variables at the beginning after document.ready
    
    $(".plcardFirst").change(function() {
    valueFirst = $( ".plcardFirst" ).val();
            });
    $(".plcardSecond").change(function() {
    valueSecond = $( ".plcardSecond" ).val();
        });
    
    // now you can use valueFirst and valueSecond of course if $( ".plcardFirst" ).val() and $( ".plcardSecond" ).val(); return something
    
    //example if(valueFirst == valueSecond){alert('both values are equal ');}
    });
    

    【讨论】:

      【解决方案2】:

      用作

       var valueFirst =0,valueSecond =0;
       (document).ready(function () {
             $(".plcardFirst").change(function() {
                  valueFirst = $( ".plcardFirst" ).val();
             });
             $(".plcardSecond").change(function() {
                 valueSecond = $( ".plcardSecond" ).val();
             });
       });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-17
        • 1970-01-01
        相关资源
        最近更新 更多