Gow*_*ham 2 javascript jquery google-chrome protractor google-chrome-console
您好,我正在尝试使用 chrome 控制台获取内部元素,但它抛出了一个错误,这是我的代码片段。任何解决方法都会真正帮助我获取元素并使其自动化。我附上了一个常见网站的截图
当我这样做时,我将类元素(ieswatches-wrap)列表作为数组获取。
$$(`.swatches-wrap`);
Run Code Online (Sandbox Code Playgroud)
当我尝试这样做时,它会抛出一个错误Uncaught TypeError: $$(...)[0].$ is not a function
$$(`.swatches-wrap`)[0].$(`.title`);
Run Code Online (Sandbox Code Playgroud)
$是$$chrome 提供的 devtools 实用程序 api 的一部分(https://developers.google.com/web/tools/chrome-devtools/console/utilities)
$是一个快捷方式document.querySelector并返回与查询匹配的第一个元素。默认情况下,它从根元素 ( body) 开始,并且可以通过提供第二个参数来覆盖根元素。
$$是一个快捷方式[...document.querySelectorAll('some query')]并返回与查询匹配的元素数组。默认情况下,它从根元素 ( body) 开始,并且可以通过提供第二个参数来覆盖根元素。
对于您的示例,这应该是一种更好的方法,同时也可以作为如何使用 root 参数的示例:
$('.title',$('.swatches-wrap'))
Run Code Online (Sandbox Code Playgroud)
由于 CSS 选择器的工作方式,执行示例的最有效方法是
$('.swatches-wrap .title')
Run Code Online (Sandbox Code Playgroud)
如果您正在元素内寻找多个.title标签.swatches-wrap:
$$('.swatches-wrap .title').forEach( elem => {
console.log('found another `.swatches-wrap .title` ', element)
})
Run Code Online (Sandbox Code Playgroud)
重要的是要记住,这些都是实用函数,并且它们仅存在于 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)
})
Run Code Online (Sandbox Code Playgroud)
document.querySelectorAll返回一个类似数组的对象,可以通过将其扩展为新数组来将其转换为数组。这就是[...<expression>]所做的
最后,如果您想在代码中获得相同的$实用$$程序,则不必使用 jQuery,您可以将其放入代码中并使用$,$$就像我们在上面的示例中所做的那样:
// $ polyfill
const $ = document.querySelector.bind(document)
// $$ polyfill
const $$ = (selector, root)=>[...document.querySelectorAll(selector,root)]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6875 次 |
| 最近记录: |