javascript 使用 querySelectorAll 选择多个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20677933/
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
Selecting multiple elements with querySelectorAll
提问by A1rPun
I have this piece of code:
我有这段代码:
var requiredFields = el.querySelectorAll("input[required]:not(:disabled):not([readonly]):not([type=hidden])");
If I want to add the textarea
and select
to the query I'm ending up with this:
如果我想将textarea
和添加select
到查询中,我将得到以下结果:
var requiredFields = el.querySelectorAll("input[required]:not(:disabled):not([readonly]):not([type=hidden])"+
",select[required]:not(:disabled):not([readonly]):not([type=hidden])"+
",textarea[required]:not(:disabled):not([readonly]):not([type=hidden])");
My feeling says this could be better.. but how?
我的感觉说这可能会更好..但是如何?
Bonus: Please give me a good resource for querySelectorAll function.
奖励:请给我一个关于 querySelectorAll 函数的好资源。
采纳答案by T.J. Crowder
As Shadow Wizard said, at a minimum you can remove the unnecessary :not([type=hidden])
in the various places it has no meaning (select
and textarea
).
正如Shadow Wizard所说,至少你可以:not([type=hidden])
在它没有意义的各个地方删除不必要的(select
和textarea
)。
I don't see a problem with the result:
我认为结果没有问题:
var requiredFields = el.querySelectorAll(
"input[required]:not(:disabled):not([readonly]):not([type=hidden])" +
",select[required]:not(:disabled):not([readonly])"+
",textarea[required]:not(:disabled):not([readonly])");
...not least because it hands the whole thing off to the selector engine to take advantage of any optimization it can do.
...尤其是因为它将整个事情交给选择器引擎以利用它可以做的任何优化。
Alternately you could give all of the relevant inputs a common class and then use:
或者,您可以为所有相关输入提供一个通用类,然后使用:
var requiredFields = el.querySelectorAll(
".the-class[required]:not(:disabled):not([readonly]):not([type=hidden])");
...but I'm not sure it buys you much.
...但我不确定它能给你带来多少。
Please give me a good resource for querySelectorAll function.
请给我一个很好的 querySelectorAll 函数资源。
There's the specification. MDNis also usually a good place for this stuff.
回答by GLES
window.l = ['input','textarea','select'];
function myQuerySelectorAll() {
q = '';
t = '[required]:not(:disabled):not([readonly]):not([type=hidden])';
l.forEach(function(e) {
q += e;
q += t;
q += ',';
});
console.log(q)
}
$> myQuerySelectorAll();
$> input[required]:not(:disabled):not([readonly]):not([type=hidden]),textarea[required]:not(:disabled):not([readonly]):not([type=hidden]),select[required]:not(:disabled):not([readonly]):not([type=hidden]),