如何在 querySelectorAll 的过滤函数中引用 "this"?

How do I refer to "this" inside filter function of querySelectorAll?

我的 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的第一个参数,它指的是被迭代的当前元素。

或者,由于看起来您只需要 第一个 匹配项,请改用 .find

const title = Array.from(document.querySelectorAll("meta"))
  .find(function (meta) {
    return String(meta.getAttribute('property')).endsWith("title");
  })
  .getAttribute('content');

您也可以在 Cheerio 中做同样的事情,除了被迭代的元素是 both 放入 this and 进入第二个参数。

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")