,*").find("li") is better than $(&qu"/> ,*").find("li") is better than $(&qu">

Home  >  Article  >  Web Front-end  >  The rephrased title is: Rarely Used jQuery Selectors

The rephrased title is: Rarely Used jQuery Selectors

WBOY
WBOYOriginal
2023-09-03 11:57:11969browse

重新表述的标题为:Rarely Used jQuery Selectors

Selectors are crucial. Most jQuery methods require some sort of element selection to work. For example, attaching a click event to a button requires that you select the button first.

Because common jQuery selectors are based on existing CSS selectors, you are probably very familiar with them. However, there are some selectors that are not widely used. In this tutorial, I'll focus on these lesser-known but important selectors.

All selectors (*)

This selector is correctly called a universal selector because it selects all elements in the document, including , class="inline">

, <script></script> or <link> tags. This demo should illustrate my point. <pre class="brush:javascript;toolbal:false;">$(&quot;section *&quot;) // Selects all descendants $(&quot;section &gt; *&quot;) // Selects all direct descendants $(&quot;section &gt; * &gt; *&quot;) // Selects all second level descendants $(&quot;section &gt; * &gt; * a&quot;) // Selects 3rd level links </pre> <p>This selector can be very slow if used in combination with other elements. However, it all depends on how the selector is used and in which browser it is executed. In Firefox, <code class="inline">$("#selector > *").find("li") is better than $("#selector > ul").find("li"). Interestingly, Chrome does $("#selector > *").find("li") slightly faster. All browsers execute $("#selector *").find("li") slower than $("#selector ul").find("li"). I recommend you compare performance before using this selector.

Here is a demonstration comparing the execution speed of the all selector.

Animated Selector (:animated)

You can use the :animated selector to select all elements whose animation is still in progress while this selector is running. The only problem is that it will only select elements that are animated using jQuery. This selector is a jQuery extension and does not benefit from the performance improvements of the native querySelectorAll() method.

Also, you cannot detect CSS animations using jQuery. However, you can use the animationend event to detect when the animation ends.

Watch the demo below.

In the above demo, only odd div<code class="inline"> elements are animated before executing $(":animated").css("background","#6F9"); .So, only those div elements will change to green. After that, we call the animate function on the rest of the div element. If you click the button now, all div elements should turn green.

Attribute is not equal to selector ([attr!="value"])

Universal attribute selectors typically detect whether an attribute with a given name or value exists. On the other hand, the [attr!="value"] selector will select all elements that do not have the specified attribute or that attribute exists but is not equal to a specific value. It is equivalent to :not([attr="value"]). Unlike [attr="value"], [attr!="value"] is not part of the CSS specification. Therefore, using $("css-selector").not("[attr='value']") can improve performance in modern browsers.

The following code snippet adds the mismatch class to all li elements whose data-category attribute is not equal to css. This Helpful when debugging or setting correct property values ​​using JavaScript.

$("li[data-category!='css']").each(function() {
  $(this).addClass("mismatch");
  // Adds a mismatch class to filtered out selectors.
  
  $(".mismatch").attr("data-category", attributeValue);
  // Set correct attribute value
});

In the demo, I checked both lists and corrected the value of the element's category attribute.

Contains selector (:contains(text))

This selector is used to select all elements containing the specified string. The match string can be located directly inside the relevant element or within any of its descendants.

The example below should help you understand this selector better. We will add a yellow background to all occurrences of the phrase Lorem Ipsum.

Let’s start with the tags:

<section>
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
    has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</p>
  <p>It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of <b>Lorem Ipsum</b>.</p>
  <a href="https://en.wikipedia.org/wiki/Lorem_ipsum">Lorem Ipsum Wikipedia Link</a>
</section>
<section>
  <p>This <span class="small-u">lorem ipsum</span> should not be highlighted.</p>
</section>
<ul>
  <li>A Lorem Ipsum List</li>
  <li>More Elements Here</li>
</ul>

Observe that the phrase Lorem Ipsum appears in seven different places. I intentionally use small caps in one instance to indicate that the match is case-sensitive.

Here is the JavaScript code that highlights all matches:

$("section:contains('Lorem Ipsum')").each(function() {
  $(this).html(
      $(this).html().replace(/Lorem Ipsum/g, "<span class='match-o'>Lorem Ipsum</span>")
    );
});

Quotes around strings are optional. This means that $("section:contains('Lorem Ipsum')") and $("section:contains(Lorem Ipsum)") are both valid in the above snippet . I'm only targeting some elements, so the Lorem Ipsum text within the list elements should remain unchanged. Additionally, the text within the second section element should not be highlighted due to a case mismatch. As you can see in this demo, that's exactly what happens.

有选择器 (:has(selector))

此选择器将选择至少包含一个与给定选择器匹配的元素的所有元素。需要匹配的选择器不必是直接子级。 :has() 不是 CSS 规范的一部分。在现代浏览器中,您应该使用 $("pure-css-selector").has(selector) 而不是 $("pure-css-selector:has(选择器)") 以提高性能。

此选择器的一个可能的应用是操作其中包含特定元素的元素。在我们的示例中,我将更改内部包含链接的所有列表元素的颜色。

这是演示的标记:

<ul>
  <li>Pellentesque <a href="dummy.html">habitant morbi</a> tristique senectus.</li>
  <li>Pellentesque habitant morbi tristique senectus.</li>
  (... more list elements here ...)
  <li>Pellentesque habitant morbi tristique senectus.</li>
  <li>Pellentesque <a href="dummy.html">habitant morbi</a> tristique senectus.</li>
</ul>

以下是更改列表元素颜色的 JavaScript 代码:

$("li:has(a)").each(function(index) {
  $(this).css("color", "crimson");
});

这段代码背后的逻辑非常简单。我循环遍历所有包含链接的列表元素并将其颜色设置为深红色。您还可以操作列表元素内的文本或将它们从 DOM 中删除。我确信这个选择器可以用在很多其他情况下。在 CodePen 上查看此代码的实时版本。

基于索引的选择器

除了像 :nth-child() 这样的 CSS 选择器之外,jQuery 也有自己的一组基于索引的选择器。这些选择器是 :eq(index):lt(index):gt(index)。与基于 CSS 的选择器不同,这些选择器使用从零开始的索引。这意味着 :nth-child(1) 将选择第一个子级,而 :eq(1) 将选择第二个子级。要选择第一个孩子,您必须使用 :eq(0)

这些选择器也可以接受负值。当指定负值时,将从最后一个元素开始向后计数。

:lt(index) 选择索引小于指定值的所有元素。要选择前三个元素,您将使用 :lt(3)。这是因为前三个元素的索引值分别为 0、1 和 2。使用负索引将选择向后计数后到达的元素之前的所有值。同样,:gt(index) 选择索引大于指定值的所有元素。

:lt(4)  // Selects first four elements
:lt(-4) // Selects all elements besides last 4
:gt(4)  // Selects all elements besides first 5
:gt(-4) // Selects last three elements
:gt(-1) // Selects Nothing
:eq(4)  // Selects fifth element
:eq(-4) // Selects fourth element from last

尝试单击演示中的各个按钮以更好地了解索引选择器。

表单选择器

jQuery 定义了许多选择器,以便轻松选择表单元素。例如, :button 选择器将选择所有按钮元素以及按钮类型的元素。同样, :checkbox 将选择所有类型为 checkbox 的输入元素。几乎所有输入元素都定义了选择器。考虑下面的表格:

<form action="#" method="post">
  <div>
    <label for="name">Text Input</label>
    <br>
    <input type="text" name="name" />
    <input type="text" name="name" />
  </div>
  <hr>
  <div>
    <label for="checkbox">Checkbox:</label>
    <input type="checkbox" name="checkbox" />
    <input type="checkbox" name="checkbox" />
    <input type="checkbox" name="checkbox" />
    <input type="checkbox" name="checkbox" />
  </div>
</form>

我在这里创建了两个文本元素和四个复选框。该表单非常基本,但它应该让您了解表单选择器的工作原理。我们将使用 :text 选择器计算文本元素的数量,并更新第一个文本输入中的文本。

var textCount = $(":text").length;
$(".text-elements").text('Text Inputs : ' + textCount);

$(":text").eq(0).val('Added programatically!');

我使用 :text 选择所有文本输入,然后使用 length 方法来计算它们的数量。在第三条语句中,我使用前面讨论的 :eq() 选择器来访问第一个元素,然后设置其值。

请记住,从 jQuery 1.5.2 开始,对于未指定任何 type 属性的元素,:text 返回 true

看看演示。

标头选择器 (:header)

如果您想选择网页上的所有标题元素,可以使用简短的 $(":header") 版本,而不是详细的 $ ("h1 h2 h3 h4 h5 h6") 选择器。此选择器不是 CSS 规范的一部分。因此,首先使用纯 CSS 选择器,然后使用 .filter(":header") 可以获得更好的性能。

例如,假设网页上有一个 article 元素,并且它具有三个不同的标题。现在,为了简洁起见,您可以使用 $("article :header") 而不是 $("article h1,article h2,article h3")。为了使其更快,您可以使用 $("article").filter(":header")。这样您就可以两全其美。

要对所有标题元素进行编号,您可以使用以下代码。

$("article :header").each(function(index) {
  $(this).text((index + 1) + ": " + $(this).text());
  // Adds numbers to Headings
});

尝试一下随附的演示。

最终想法

在本教程中,我讨论了使用 jQuery 时可能遇到的不常见选择器。虽然大多数选择器都有可供您使用的替代方案,但了解这些选择器的存在仍然是件好事。

我希望您在本教程中学到了一些新东西。如果您有任何问题或建议,请评论。

The above is the detailed content of The rephrased title is: Rarely Used jQuery Selectors. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn