为什么我的var在上一个函数中被设置时却变得未定义



目前我正在尝试模拟登录/注册表单,但目前遇到了一个问题,我似乎找不到解决方案,它说我的"用户名"未定义,但首先运行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)
}

我想这可能是因为它不是全球范围?如果是这样的话,我怎么会想到用这个代码来做呢?

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'  

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

不要使用已经声明为函数的参数的变量。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)
}

相关内容

最新更新