JavaScript函数内的变量声明

4

我是javascript的新手,我想了解为什么这段代码没有效果:

var firstName = $("#firstName").val();

$("#account").on('submit', function() {
     console.log(firstName); // Empty value
});

jsfiddle: FIDDLE

7个回答

4

你的代码在页面首次加载时获取了firstname字段的值,并将其存储在变量firstName中。然后,稍后它会将存储的值输出到控制台。如果你想要该字段的当前值,你必须在输出时获取当前值,就像这样:

$("#account").on('submit', function() {
     var firstName = $("#firstName").val();   // get current value
     console.log(firstName); 
});

3

您正在获取输入的初始值并将其存储在字符串变量中。相反,应该将jQuery对象引用存储在变量中,以便在需要时获取值。

var firstName = $("#firstName");

$("#account").on('submit', function() {
  console.log(firstName.val());
});

var firstName = $("#firstName");

$("#account").on('submit', function() {
  console.log(firstName.val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="account" method="post">
  <input type="text" id="firstName">
  <input type="submit">
</form>


太好了!它完全按照我的需求工作(在函数外使用function(){});非常感谢你。 - Amanda Thompson

1
因为它一直保持默认值。您需要在提交表单时获取该值。
var firstNameDefault = $("#firstName");

$("#account").on('submit', function() {
    var firstNameAfterClick = $("#firstName");
    console.log(firstName.val()); // Empty value
    console.log(firstNameAfterClick.val()); // Should display value of #firstName after form is submitted
});

0
var firstName = $("#firstName").val(); // move this line from here to inside the function

$("#account").on('submit', function() {
     var firstName = $("#firstName").val();
     console.log(firstName); // Empty value
});

0

要使其工作,需要在提交时获取输入的值,而不是在之前。

$("#account").on('submit', function() {
     var firstName = $("#firstName").val();
     console.log(firstName); // non-empty value
});

0

它实际上是在工作的。只是变量username没有从$("#firstName")获取最新值。

以下是发生的示例:

var firstName = $("#firstName").val(); // this line says that get the value of #firstName

例如,#firstName 是一个文本框,由于您尚未对其进行任何赋值,因此它很可能具有空值。除非您对其进行任何赋值,否则第一行始终会有空数据。
$("#account").on('submit', function() {
     console.log(firstName); // Empty value
});

这一行代码是在#account被提交时,在控制台打印firstName里面的内容。但是你得到了之前的值,因为你检索了#firstName第一个值。 如果你想要打印当前或最新的#firstName的值,请看看其他人的答案。 我只是解释了你的代码中实际发生了什么。


0

我假设你在#firstName中有一个默认值,你想在浏览器控制台中看到这个默认值而不进行任何更改。由于表单提交后页面会刷新,所以你无法看到控制台的值。因此,只需再添加一行return false;就可以在控制台中看到它。

<script>
    var firstName = $("#firstName").val();

    $("#account").on('submit', function() {
        console.log(firstName); 
        return false;
    });
</script>

*** 不要忘记在调试完成后删除 return false;,否则表单将无法提交到服务器。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接