【发布时间】:2021-11-04 18:14:33
【问题描述】:
我正在创建动态跨度标签以在表单字段下方显示错误消息。在每次扫描错误之前,我想清除旧的错误范围,但不知何故,清除函数中任何地方的“警报”语句都会延迟删除操作。谁能解释或帮助我改写这种行为?下面是一个非常简单的演示:
<html>
<style>
.errorContainer {
color: red;
display: block;
font-weight: bold;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
function DisplayErrors() {
var es = document.createElement("SPAN");
es.className = "errorContainer";
es.textContent = "First Name is required.";
document.getElementById("firstName").after(es);
var es = document.createElement("SPAN");
es.className = "errorContainer";
es.textContent = "Last Name is required.";
document.getElementById("lastName").after(es);
}
function RemoveErrors() {
$(".errorContainer").remove();
alert("hold");
}
</script>
<body>
<table>
<tr>
<td>First Name: </td>
<td><input id="firstName" name="firstName" type="text" maxlength="20"></td>
</tr>
<tr>
<td>Last Name: </td>
<td><input id="lastName" name="lastName" type="text" maxlength="20"></td>
</tr>
</table>
<input type="button" onclick="DisplayErrors();" value="Display Errors">
<input type="button" onclick="RemoveErrors();" value="Remove Errors">
</body>
</html>
【问题讨论】:
-
浏览器不会更新显示,直到 JavaScript 函数返回,
alert()同步并阻塞。
标签: javascript jquery dynamic