有一个网页包含一定数量的必填字段,需要填写这些字段才能成功提交表单。 必填字段的最大标志是它有一个 * 并且它的标签中有一个“必填”类。 当我们更改下拉值时,必填字段的数量会发生变化。我编写了一些 javascript 和 jquery 代码来更改下拉值,然后检查必填字段的数量,但由于某种原因(很可能 DOM 更改需要时间并且代码在此之前执行,因此实际上未反射(reflect)必填字段数量的变化在页面中)。但是,如果我手动更改下拉值,然后运行 checkRequired() 函数,它工作正常,但我想自动化该过程。我怎样才能实现这一目标?
var count = 0;
var allRequired = []; // total number of required fields in the page
var newRequired = []; // change in the no. of required fields
$('select').each(function(){
var id = $(this).attr('id');
$('#'+id+' option').each(function() {
$(this).attr('selected','selected');
if(count == 0){
getAllRequiredFields();
}
else{
setTimeout(() => {
checkRequired();
for (let index = 0; index < allRequired.length; index++) {
console.log('for else',allRequired[index]);
if(!newRequired.includes(allRequired[index])){
console.log('allRequired',allRequired[index]);
}
}
}, 3000);
}
count++;
})
});
function getAllRequiredFields(){
$('span.required').each(function () {
var text = $(this).parent().text()
var id = $(this).closest("td").attr('id').split("_label")[0];
allRequired.push(id);
});
}
function checkRequired() {
newRequired = [];
$('span.required').each(function () {
var text = $(this).parent().text()
var id = $(this).closest("td").attr('id').split("_label")[0];
newRequired.push(id);
});
for (let index = 0; index < allRequired.length; index++) {
console.log('for else',count);
if(!newRequired.includes(allRequired[index])){
console.log('allRequired',allRequired[index]);
}
}
}
最佳答案
刚刚添加的更改事件解决了我的问题
$('#'+id+' option').each(function() {
$(this).attr('selected','selected');
$('#'+id).change();
if(count == 0){
getAllRequiredFields();
}
else{
setTimeout(() => {
checkRequired();
for (let index = 0; index < allRequired.length; index++) {
console.log('for else',allRequired[index]);
if(!newRequired.includes(allRequired[index])){
console.log('allRequired',allRequired[index]);
}
}
}, 3000);
}
count++;
})
关于javascript - 使用 Select Option 更改 DOM 并检查是否有必填字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51712189/