检查HTML表单是否被编辑可以通过以下几种方式实现:
示例代码:
var formEdited = false;
function checkFormEdited() {
formEdited = true;
}
// 监听输入框变化
var inputElements = document.querySelectorAll('input');
for (var i = 0; i < inputElements.length; i++) {
inputElements[i].addEventListener('input', checkFormEdited);
}
// 监听下拉菜单变化
var selectElements = document.querySelectorAll('select');
for (var i = 0; i < selectElements.length; i++) {
selectElements[i].addEventListener('change', checkFormEdited);
}
// 监听复选框变化
var checkboxElements = document.querySelectorAll('input[type="checkbox"]');
for (var i = 0; i < checkboxElements.length; i++) {
checkboxElements[i].addEventListener('change', checkFormEdited);
}
// 监听单选框变化
var radioElements = document.querySelectorAll('input[type="radio"]');
for (var i = 0; i < radioElements.length; i++) {
radioElements[i].addEventListener('change', checkFormEdited);
}
示例代码:
var initialFormValues = {};
function recordInitialFormValues() {
var inputElements = document.querySelectorAll('input');
for (var i = 0; i < inputElements.length; i++) {
initialFormValues[inputElements[i].name] = inputElements[i].value;
}
var selectElements = document.querySelectorAll('select');
for (var i = 0; i < selectElements.length; i++) {
initialFormValues[selectElements[i].name] = selectElements[i].value;
}
var textareaElements = document.querySelectorAll('textarea');
for (var i = 0; i < textareaElements.length; i++) {
initialFormValues[textareaElements[i].name] = textareaElements[i].value;
}
}
function checkFormEdited() {
for (var key in initialFormValues) {
var currentValue = document.getElementsByName(key)[0].value;
if (currentValue !== initialFormValues[key]) {
console.log('Form edited');
return;
}
}
console.log('Form not edited');
}
示例代码(使用jQuery):
var formEdited = false;
$(document).ready(function() {
$('input, select, textarea').on('change', function() {
formEdited = true;
});
});
以上是检查HTML表单是否被编辑的几种方法,根据具体需求选择适合的方式。
领取专属 10元无门槛券
手把手带您无忧上云