gpt4 book ai didi

javascript - 如何恢复 DOM 所做的更改?

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

所以我制作了一个简单的 javascript 表单验证器,它使用 DOM 创建一个包含错误消息的框。但当我使用重置表单时,我无法找出如何重置所有这些更改的方法 <button type="reset">

我想知道它是如何完成的。

谢谢。

代码

<html>
<head>
<script type="text/javascript">
function validate(){
var fname = document.getElementById("fname");
var surname = document.getElementById("surname");

if(fname.value === "" || fname.value === null){
document.getElementById("sbody").style.display = "block";
document.getElementById("fname").style.display = "block";
return false;
}

//Verify Last Name
if(surname.value === "" || surname.value === null){
document.getElementById("sbody").style.display = "block";
document.getElementById("surname").style.display = "block";
return false;
}
}//End Validate Function
</script>


<style type="text/css">
#sbody{
width: 100px;
height: 100px;
background-color: #f3f3f3;
display:none;
}

.vis{
display: none;
font-size: 12px;
}
</style>
</head>

<body>
<section id="sbody">
<span id="fner" class="vis">First Name is missing.</span>
<span id="lner" class="vis">Surame is missing.</span>
</section>

<form id="registerForm" method="POST" action="register.php" onsubmit="return validate()">
<label for="fname" class="labelStyle">First Name: </label>
<input id="fname" name="fname" type="text" value="">

<label for="surname" class="labelStyle">Surname: </label>
<input id="surname" name="surname" type="text" value="">

<button type="submit">Sign Up</button>
<button type="reset">Reset</button>
</form>
</body>
</html>

最佳答案

浏览器无法神奇地弄清楚需要做什么来重置自定义更改。

但是您可以收听 reset使用element.addEventListener形式的事件.

DEMO

HTML

<form id="test">
<div id="errors-ct">The form has errors</div>
<button type="reset">Reset</button>
</form>

JS

//wait for the DOM to be ready
document.addEventListener('DOMContentLoaded', function () {
//store a reference to the errors container div
var errorsCt = document.getElementById('errors-ct');

//listen to the reset event of the form
document.getElementById('test').addEventListener('reset', function (e) {
var form = e.target; //this is how you could access the form

//hide the errors container
errorsCt.style.display = 'none';
});
});

关于javascript - 如何恢复 DOM 所做的更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19890430/

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