JavaScript范围错误 - 返回未定义的

时间:2018-03-14 14:51:43

标签: javascript jquery

我似乎无法理解为什么我的fullName变量在控制台中返回undefined。它将从单击函数中的警告框中的输入返回文本。但在点击功能之外,fullName会返回undefined。这是代码:

var fullName, firstName, middleName, lastName, middleInitials;

$(document).ready(function() {


  $("#nameButton").click(function(event){  // upon clicking the event file
     fullName = $("#name").val().toString();  // that's a jquery function
     alert("fullname" + fullName + ", typeof = " + typeof fullName);  // 20:44 shows correct name
     console.log(typeof fullName); // does not display in console 
    console.log(fullName); // does not display in console
  });

  console.log("fullName = " + fullName);  // 20:44 Shows undefined 

}); // the jquery one

2 个答案:

答案 0 :(得分:4)

$(document).ready(function() {执行fullname变量时undefined。当您单击按钮时,它将设置变量,但到那时$(document).ready(function() {已经执行...这意味着console.log("fullName = " + fullName);已经执行。

答案 1 :(得分:1)

如果在文档准备就绪时加载了元素,则应在单击发生之前定义变量,如果要查看其内容。

$(document).ready(function() {
  // define the full name here. 
  fullName = $("#name").val().toString();  // that's a jquery function

  $("#nameButton").click(function(event){  // upon clicking the event file
     alert("fullname" + fullName + ", typeof = " + typeof fullName);  // 20:44 shows correct name
     console.log(typeof fullName); // does not display in console 
    console.log(fullName); // does not display in console
  });

  console.log("fullName = " + fullName);  // This should work now. 

});