javascript 使用带有 querySelectorAll 的innerHTML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27983388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:15:19  来源:igfitidea点击:

Using innerHTML with querySelectorAll

javascript

提问by user2265915

I want to use something similar to the following to clear errors in a form upon a resubmission attempt:

我想在重新提交尝试时使用类似于以下内容的内容来清除表单中的错误:

document.querySelectorAll("#form-error-name, #form-error-email, #form-error-tel, #form-error-dob, #form-error-password, #form-error-goal").innerHTML= "";

...But the contents of the divs isn't cleared. What am I doing wrong?

...但是 div 的内容没有被清除。我究竟做错了什么?

采纳答案by atmd

You'll need to loop through the results

您需要遍历结果

    var errors = document.querySelectorAll(
               "#form-error-name, 
                #form-error-email, 
                #form-error-tel, 
                #form-error-dob, 
                #form-error-password, 
                #form-error-goal");

[].forEach.call(errors, function(error) {
  error.innerHTML = '';
});

querySelectorAlldoesn't return an array, but a node list, which doesn't have a forEachmethod on its prototype.

querySelectorAll不返回数组,而是返回一个节点列表,forEach它的原型上没有方法。

The loop above is using the forEachmethod on the array object's prototype on the nodeList object.

上面的循环forEach在 nodeList 对象上使用数组对象的原型上的方法。

回答by Gaurav Dave

Try this:

试试这个:

var x = document.querySelectorAll("#form-error-name, #form-error-email, #form-error-tel");
var i;
for (i = 0; i < x.length; i++) {
    x[i].innerHTML = "";
}

See, if that helps.

看看,如果这有帮助。

回答by John Haugeland

The appropriate modern answer would be

适当的现代答案是

[... document.querySelectorAll('input')].map(i => i.value = '');