gpt4 book ai didi

javascript - 我添加的事件处理程序仅在页面加载时工作一次

转载 作者:行者123 更新时间:2023-11-28 04:58:57 27 4
gpt4 key购买 nike

我正在尝试检查用户是否在字段仍为空时更改字段。并且我在用户名字段上添加事件监听器,以便当用户从一个字段移动到另一个字段时,他会收到检查符号或错误。
我的 HTML 文件:

<!DOCTYPE html>
<html>
<head>
<title>Registeration form</title>
<link type="text/css" rel="stylesheet" href="css/fontawesome.css"/>
</head>
<body>
<form method="post">
<fieldset>
<input type="text" name="user_name" id="user_name" style="display:inline;float:left;" placeholder="User Name">
<li id="name_status" style="list-style-type:none;"></li>
</fieldset>
<fieldset>
<input type="text" name="email" id="email" style="display:inline;float:left;" placeholder="Email Address">
<li id="email_status" style="list-style-type:none;"></li>
</fieldset>
<fieldset>
<input type="button" name="submit" id="submit" value="submit">
</fieldset>
</form>
<script type="text/javascript" src="js/test.js"></script>
</body>
</html>

我的 JavaScript 文件:

var user_name=document.getElementById("user_name");
var user_name_status=document.getElementById("name_status");

user_name.addEventListener("blur",check_empty(user_name.value,user_name_status),false);
function check_empty(value,status){
if(value.length===0){
status.innerHTML="<sup>*</sup>This feild cannot be empty";
} else {
status.innerHTML="<i class='icon-check'></i>";
}
}

最佳答案

您正在立即调用check_empty。您可以将函数引用 check_empty 传递给 .addEventListener()。在事件处理程序中,this 引用user_name。不要传递变量 status,而是在事件处理程序中使用定义的变量 user_name_status

var user_name = document.getElementById("user_name");
var user_name_status = document.getElementById("name_status");

user_name.addEventListener("blur", check_empty, false);

function check_empty(e) {
if (this.value.length === 0) {
user_name_status.innerHTML = "<sup>*</sup>This feild cannot be empty";
} else {
user_name_status.innerHTML = "<i class='icon-check'>check</i>";
}
}
<!DOCTYPE html>
<html>

<head>
<title>Registeration form</title>
</head>

<body>
<form method="post">
<fieldset>
<input type="text" name="user_name" id="user_name" style="display:inline;float:left;" placeholder="User Name">
<li id="name_status" style="list-style-type:none;"></li>
</fieldset>
<fieldset>
<input type="text" name="email" id="email" style="display:inline;float:left;" placeholder="Email Address">
<li id="email_status" style="list-style-type:none;"></li>
</fieldset>
<fieldset>
<input type="button" name="submit" id="submit" value="submit">
</fieldset>
</form>
</body>

</html>

关于javascript - 我添加的事件处理程序仅在页面加载时工作一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42319005/

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