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
Using innerHTML with querySelectorAll
提问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 = '';
});
querySelectorAll
doesn't return an array, but a node list, which doesn't have a forEach
method on its prototype.
querySelectorAll
不返回数组,而是返回一个节点列表,forEach
它的原型上没有方法。
The loop above is using the forEach
method 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 = '');