0

嗨,我正在尝试使用 chrome 控制台获取内部元素,但它给我一个错误,这是我的代码片段。任何解决方法都将真正帮助我获取元素并将其自动化。我附上了一个常见网站的截图

当我这样做时,我将类元素列表(ieswatches-wrap)作为数组获取。

$$(`.swatches-wrap`);

当我尝试这个时,它给我一个错误Uncaught TypeError: $$(...)[0].$ is not a function

$$(`.swatches-wrap`)[0].$(`.title`);

这是随附的屏幕截图 在此处输入图像描述

4

3 回答 3

2

$(".swatches-wrap")[0].querySelector(".info")

  • 返回第一个找到的元素

  • null如果没有找到则返回

你也可以链接它,除非它是null

$(".swatches-wrap")[0].querySelector(".info").querySelector(".something")

于 2019-12-10T07:44:17.247 回答
2

$并且$$是 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)]
于 2019-12-10T08:24:59.190 回答
1

也许你可以试试

$($(".swatches-wrap")[0]).children(".title")

有什么不同(以堆栈页面为例):

  1. 如果你使用这个↓,会得到一个DOM。

    $(".li")[0]

    一个 HTML DOM

  2. 如果你使用这个↓,会得到一个Object。

    $(".-img _glyph")

    一个对象

于 2019-12-10T08:03:30.060 回答