Chrome DevTools:$(选择器)速记不返回元素,而$$(选择器)[0]返回元素 [英] Chrome DevTools: $(selector) shorthand doesn't return the element while $$(selector)[0] does

查看:32
本文介绍了Chrome DevTools:$(选择器)速记不返回元素,而$$(选择器)[0]返回元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用$Chrome API速记为document.querySelector时,我经常遇到一个奇怪的现象,即它没有使用正确的选择器返回元素,而使用$$却可以正常工作。由于puppeteer严重依赖这些速记(page.$page.$$page.$evalpage.$$eval),因此可能会导致意外问题。

此问题甚至可以在此处转载,目前位于堆栈溢出(2020年9月29日)。

例如:

  • $('h1').innerText=>;undefined

  • $$('h1')[0].innerText=>;Chrome DevTools: $(selector) shorthand doesn't return the element...

原因是什么,使用$$的解决方法为什么有效?

推荐答案

我发现它会影响那些在前端使用jQuery库的页面(Stack Overflow目前正在使用它)。

在这样的页面上,$被jQuery占据(作为其自身的别名),因此Chrome API返回一个对象,而不是$(selector)的元素。第一个元素是DOM元素本身,这就是[0]工作的原因。

顺便说一下:$$(selector)[0]甚至可以替换为$(selector)[0],因为这个问题与querySelectorquerySelectorAll无关。

使用jQuery的页面:

$('h1')

n.fn.init(2) [h1.grid--cell.fs-headline1.fl1.ow-break-word.mb8, h1#feed-modal-title.s-modal--header.fw-bold.js-first-tabbable.c-move, prevObject: n.fn.init(1), context: document, selector: "h1"]

$('h1')[0]/document.querySelector('h1')

<h1>...</h1>

不使用jQuery:

.虽然页面上不依赖jQuery,但它照常工作。

$('h1')/document.querySelector('h1')

<h1>...</h1>

$('h1')[0]

undefined

它可能对其他人有用。

这篇关于Chrome DevTools:$(选择器)速记不返回元素,而$$(选择器)[0]返回元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆