首页 > 解决方案 > 我想知道以下代码的功能是什么

问题描述

我试图了解以下 jquery 代码将返回什么?

$(`:contains("keyword"):not(:has(:contains("keyword")))`)

标签: javascriptjquerydom

解决方案


查看文档

描述:选择至少包含一个与指定选择器匹配的元素的元素。

$( "div:has(p)" )如果 a存在于其后代中的任何位置,则表达式匹配 a <p>,而不仅仅是作为直接子代。

因此,:contains("keyword"):not(:has(:contains("keyword")))将选择一个包含 的元素keyword,但没有任何包含的后代keyword。换句话说,keyword必须在父级中,但不能在父级的任何子级中。例如:

const match = $(`div:contains("keyword"):not(:has(:contains("keyword")))`);
console.log(match.length);
console.log(match[0]);
console.log(match[1]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="1" class="outer">
  keyword
  <div id="2" class="inner">
  </div>
</div>

<div id="3" class="outer">
  <div id="4" class="inner">
    keyword
  </div>
</div>

它选择第一个.outer,因为它.outer有一个直接的文本节点后代keyword。它选择第二个.inner,因为它也有一个直接的文本节点后代keyword

选择器要求它keyword位于作为所选父元素的子元素的文本节点中。

您可以使用以下 vanilla DOM 方法模拟选择器:

const match = [...document.querySelectorAll('div')]
  .filter(
    elm => [...elm.childNodes]
      .filter(({ nodeType }) => nodeType === 3) // Only look through text nodes
      .some(({ textContent }) => textContent.includes('keyword'))
  );
console.log(match.length);
console.log(match[0]);
console.log(match[1]);
<div id="1" class="outer">
  keyword
  <div id="2" class="inner">
  </div>
</div>

<div id="3" class="outer">
  <div id="4" class="inner">
    keyword
  </div>
</div>


推荐阅读