gpt4 book ai didi

Javascript - 值未传递给函数

转载 作者:行者123 更新时间:2023-11-27 22:43:48 24 4
gpt4 key购买 nike

所以我有这个表格:

<form name="login" id="login" action="" method="POST" onSubmit="return test()">
<input type="text" size="10" name="username" /><div id="wrongUser"></div>
<br />
<input type="password" size="10" name="password" /><div id="wrongPass"></div>
<br />
<input type="submit" value="submit" name="submit" /><br /><br />
</form>

还有这两个函数:

function test()
{
var user = document.login.username.value;
var pass = document.login.password.value;
if((user == "" || user == null) && (pass == "" || pass == null))
{
document.getElementById('wrongUser').innerText = "Please Enter Username";
document.getElementById('wrongPass').innerText = "Please Enter Password";
return false;
}

if(checkEmpty(user, 'wrongUser', "Please Enter Username"))
return false

if(checkEmpty(pass, 'wrongPass', "Please Enter Password"))
return false;

return true;
}

function checkEmpty(name, id, output)
{
if(name == "" || name == null)
{
document.getElementById(id).innerText = "";
document.getElementById(id).innerText = output;
return true;
}
else
return false;
}

现在功能有点用了,但不是我想的那样。如果用户只是没有输入任何内容(第一次),那么他们会收到 2 个错误。如果用户只输入用户名(第二次),那么用户名错误应该消失,但事实并非如此。如果我将它从函数中取出并用它们的正常值替换变量,那么它就可以正常工作。为什么放到这个函数里会变?

最佳答案

document.getElementById().innerText = '' 放在 else 中,而不是 if 中。因为你只在 innerText 为空时重置它,但如果它不为空你想重置 tekst:

function checkEmpty( name, id, output ) {
var elem = document.getElementById(id); // it's faster to put the element in a var

if( name === undefined || name == '' name == null )
elem.innerText = output;
return true;
else
elem.innerText = '';
return false;
}

关于Javascript - 值未传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8868310/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com