我有这个javascript代码(函数SHA-1位于外部文件中):
window.onload = validatePass;
function validatePass() {
var el = document.getElementById("oriPass");
var user_pass = el.value;
var hashed_pass = SHA1(user_pass);
var span = document.createElement("span");
el.parentNode.appendChild(span);
el.onblur = function doSomething() {
if(user_pass == null || user_pass == "") {
span.setAttribute('class','required');
span.innerHTML="this is a required field";
}
else {
if(hashed_pass != '7c4a8d09ca3762af61e59520943dc26494f8941b') {
span.setAttribute('class','required');
span.innerHTML="wrong password";
}
else {
span.setAttribute('class','required_ok');
span.innerHTML="valid password";
}
}
}
}
,这在html中:
<form name="form" method="post" action="change_pass.php">
<div class="row">
<div class="col1">write your password:<span class="required">*</span></div>
<div class="col2">
<input type="password" name="original_pass" id="oriPass" />
</div>
</div>
</form>
出于某种原因,每次测试时我得到相同的输出:“有效密码”,无论该字段是空的,有效的还是无效的。
我在这里做错了什么?
答案 0 :(得分:1)
您只在加载时设置密码变量。之后它永远不会改变。你需要在onblur函数中设置它。
答案 1 :(得分:1)
将var user_pass...
和var hashed_pass...
代码移到onblur函数中。现在只分配onload并且永远不会改变。也可以更好地使用onchange而不是onblur。
window.onload = validatePass;
function validatePass() {
var el = document.getElementById("oriPass");
var span = document.createElement("span");
el.parentNode.appendChild(span);
el.onchange = function doSomething() {
var user_pass = el.value;
var hashed_pass = SHA1(user_pass);
if(user_pass == null || user_pass == "") {
span.setAttribute('class','required');
span.innerHTML="this is a required field";
}
else {
if(hashed_pass != '7c4a8d09ca3762af61e59520943dc26494f8941b') {
span.setAttribute('class','required');
span.innerHTML="wrong password";
}
else {
span.setAttribute('class','required_ok');
span.innerHTML="valid password";
}
}
}
}