$
并且$$
是 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')
如果您正在寻找元素.title
内的多个标签.swatches-wrap
:
$$('.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)]