简体   繁体   English

输入的值作为变量未定义

[英]Input's value as variable is not defined

Got an input type text. 得到了输入文字。 Whatever entered is supposed to become a value for variable, and further on from there. 输入的任何内容都应成为变量的值,并从此继续。 Yet, i get error "Uncaught ReferenceError: emailvar is not defined" and the whole script breaks from there. 但是,我收到错误消息“ Uncaught ReferenceError:未定义emailvar”,整个脚本由此中断。

html html

<input type="text" class="signfield emfield" />
<div class="submt sbmtfrm" href="#" style="cursor:pointer;">Step 2</div>

and js 和js

$(".sbmtfrm").click(function(){
   var emailvar = $(".emfield").val();
});

You need to declare emailvar as a global variable to use it outside of that click event handler: 您需要将emailvar声明为全局变量,以便在该click事件处理程序之外使用它:

$(function()
{
    var emailvar;
    $(".sbmtfrm").click(function()
    {
       emailvar = $(".emfield").val();
    });
    function foo()
    {
        console.log(emailvar);
    }
}

In your code, emailvar is being defined in a function closure , and only that function has access to it. 在您的代码中, emailvar是在函数闭包中定义的,只有该函数才能访问它。

$(".sbmtfrm").click(function(){
   var emailvar = $(".emfield").val();
});

If you want to use emailvar outside of your jQuery event handler, you will need to first define it (not assign it, yet) outside the scope of the function. 如果要在jQuery事件处理程序之外使用emailvar ,则需要先在函数范围之外定义它(尚未分配 )。

(function(window, $) { // closure
    var emailvar;

    $(".sbmtfrm").click(function() {
        emailvar = $(".emfield").val();
    });

    // you now have access to `emailvar` in any function in this closure

}(window, jQuery));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM