$ 和 $$ 是 chrome (https://developers.google.com/web/tools/chrome-devtools/console/utilities) 提供的 devtools 实用程序 api 的一部分
$ 是document.querySelector 的快捷方式,并返回与查询匹配的第一个元素。默认情况下,它从根元素 (body) 开始,并且可以通过提供第二个参数来覆盖根元素。
$$ 是[...document.querySelectorAll('some query')] 的快捷方式,并返回与查询匹配的元素数组。默认情况下,它从根元素 (body) 开始,并且可以通过提供第二个参数来覆盖根元素。
对于您的示例,这应该是一种更好的方法,同时也可以作为如何使用 root 参数的示例:
$('.title',$('.swatches-wrap'))
由于 CSS 选择器的工作原理,最有效的示例方法是
$('.swatches-wrap .title')
如果您要在 .swatches-wrap 元素中查找多个 .title 标签:
$$('.swatches-wrap .title').forEach( elem => {
console.log('found another `.swatches-wrap .title` ', element)
})
请务必记住,这些是实用功能,并且它们仅存在于 chrome 控制台中。如果你想在你的代码中使用它,你应该使用下面的例子:
document.querySelector('.swatches-wrap .title')
// or for multiple results
[...document.querySelectorAll('.swatches-wrap .title')].forEach( elem => {
console.log('found another `.swartches-wrap .title` ', element)
})
document.querySelectorAll 返回一个类似数组的对象,可以通过将其扩展为新数组来将其转换为数组。这就是[...<expression>] 所做的
最后,如果你想在你的代码中获得相同的$ 和$$ 实用程序,你不必使用jQuery,你可以把它放在你的代码中并使用$ 和$$就像我们在上面的例子中所做的那样:
// $ polyfill
const $ = document.querySelector.bind(document)
// $$ polyfill
const $$ = (selector, root)=>[...document.querySelectorAll(selector,root)]