如何解决如何在querySelectorAll的过滤器函数中引用“ this”?
我有Cheerio代码,如下所示:
const title = $("meta")
.filter(function () {
return (
($(this).attr("property") != null &&
$(this).attr("property").endsWith("title")) ||
);
}).attr("content")
我想将此迁移到使用客户端JavaScript的puppeteer。到目前为止,我已经知道了:
const title = Array.from(document.querySelectorAll("meta")
.filter(function () {
return {
// stuck here: how do I call this?
// $(this)
我坚持使用文档查询选择器语法来引用“ this”。
解决方法
使用Array.prototype.filter
的第一个参数,它指向要迭代的当前元素。
或者,因为看起来您只想 first 匹配,请改用.find
:
const title = Array.from(document.querySelectorAll("meta"))
.find(function (meta) {
return String(meta.getAttribute('property')).endsWith("title");
})
.getAttribute('content');
您也可以在Cheerio中执行相同的操作,除了要迭代的元素都是 放入this
中参数。
const title = $("meta")
.filter(function (_,meta) {
return (
($(meta).attr("property") != null &&
$(meta).attr("property").endsWith("title"))
);
}).attr("content")
(但是this
通常用于cheerio和jQuery)
我知道了!您只需要在回调中加入一个参数即可。应该知道的。
例如:
Array.from(document.querySelectorAll("meta")
.filter(function (el) {
return el.name !== null && el.name.endsWith("title")
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。