querySelector中是否有分组功能?目前,我必须列出我要匹配的所有输入类型,这会导致像这样的多余字符串:
form.querySelectorAll('input[type=text], input[type=password], input[type=email], input[type=number]')
有没有一种方法可以消除冗余,使其看起来像这样:
form.querySelectorAll('input[type={text,password,email,number}]')
答案 0 :(得分:6)
没有内置的方法可以做到这一点,但是很容易构建自己的函数来构建这样的查询字符串,从而允许您编写更多的DRY代码:
const makeQuery = types => types.map(type => `input[type="${type}"]`).join(', ');
console.log(makeQuery(['text', 'password', 'email', 'number']))
答案 1 :(得分:4)
就CSS选择器而言,只有:matches
。除了Safari以外,它并没有太大的改进,也无法在没有任何前缀的浏览器中工作。
form.querySelectorAll(
'input:matches([type=text], [type=password], [type=email], [type=number])')
不过,您可以使用JavaScript构建字符串:
form.querySelectorAll(
'text,password,email,number'.replace(/\w+/g, 'input[type=$&]'))