【问题标题】:Why does my var become undefined yet being set in the previous function?为什么我的 var 变为未定义但在前一个函数中设置?
【发布时间】:2019-05-09 01:00:45
【问题描述】:

目前我正在尝试模拟登录/注册表单,我目前遇到了一个问题,我似乎无法找到解决方案来解决它说我的“用户名”未定义但正在运行 onReg功能第一。

var tempusername
var temppassword
var tempconpassword

var username
var password

function onReg(tempusername, temppassword, tempconpassword, username, password){

tempusername = document.querySelectorAll("[name=username]")[0].value
temppassword = document.querySelectorAll("[name=password]")[0].value
tempconpassword = document.querySelectorAll("[name=conpassword]")[0].value

if(temppassword == tempconpassword && tempusername.length>2 && temppassword.length>2 && tempconpassword.length>2 ){

    username = tempusername
    password = tempconpassword
    alert(username + " : " + password)

}
else if (password!=tempconpassword){
    alert("Password doesnt match or is to short!")

}
}

function onLogin(username,password) {
    alert("Does this work?" + username)
}

我认为这可能是因为它不是全局范围?如果是这样,我怎么会用这段代码来做呢?

【问题讨论】:

  • 你在哪里打电话给onReg
  • 您可以在 jsfiddle.net 上提交您的代码,以便社区中的任何人都可以查看它吗?
  • 在我的 html
  • 那么onReg的变量(tempusername, temppassword, tempconpassword, username, password)呢?
  • 请分享 HTML 和 js 或者在 jsfiddle.net 上提交您的代码

标签: javascript function scope var


【解决方案1】:

不要使用已经声明为函数参数变量usernamepassword 已经声明为变量,因此您应该将它们替换为其他名称。尝试改用usernameXpasswordX

function onLogin(usernameX,passwordX) {

    // will alert the value of the first parameter (usernameX)
    alert("Does this work?" + usernameX) 

    //if you want to get the value of the variable 
    alert("Does this work?" + username)

}

【讨论】:

    【解决方案2】:

    我认为你应该使用document.getElementById("[name=username]").value

    【讨论】:

      【解决方案3】:

      onLogin 里面的username 是一个正式的函数参数。在调用onLogin 时,您必须显式地向它传递一个值。

      var x = 'foo';
      function checkX() {
          alert(x);
      }  
      function badCheckX(x) {
          alert(x);
      }
      checkX(); // 'foo'
      badCheckX(); // undefined
      badCheckX('bar'); // 'bar'
      badCheckX(x); // 'foo'  
      

      【讨论】:

        猜你喜欢
        • 2012-05-31
        • 2020-09-16
        • 1970-01-01
        • 1970-01-01
        • 2020-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多