• <button id="lls9k"><b id="lls9k"></b></button>
    <\/code>,

    亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

    Table of Contents
    All selectors (*)
    Animated Selector (:animated)
    Attribute is not equal to selector ([attr!="value"])
    Contains selector (:contains(text))
    有選擇器 (:has(selector))
    基于索引的選擇器
    表單選擇器
    標(biāo)頭選擇器 (:header)
    最終想法
    Home CMS Tutorial WordPress Rarely Used jQuery Selectors

    Rarely Used jQuery Selectors

    Aug 29, 2023 pm 03:25 PM

    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 <head>, <body>, <script> or <link> Label. This demo should illustrate my point.

    $("section *")         // Selects all descendants
    $("section > *")       // Selects all direct descendants
    $("section > * > *")   // Selects all second level descendants
    $("section > * > * a") // Selects 3rd level links
    

    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, $("#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))

    此選擇器將選擇至少包含一個(gè)與給定選擇器匹配的元素的所有元素。需要匹配的選擇器不必是直接子級(jí)。 :has() 不是 CSS 規(guī)范的一部分。在現(xiàn)代瀏覽器中,您應(yīng)該使用 $("pure-css-selector").has(selector) 而不是 $("pure-css-selector:has(選擇器)") 以提高性能。

    此選擇器的一個(gè)可能的應(yīng)用是操作其中包含特定元素的元素。在我們的示例中,我將更改內(nèi)部包含鏈接的所有列表元素的顏色。

    這是演示的標(biāo)記:

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

    這段代碼背后的邏輯非常簡(jiǎn)單。我循環(huán)遍歷所有包含鏈接的列表元素并將其顏色設(shè)置為深紅色。您還可以操作列表元素內(nèi)的文本或?qū)⑺鼈儚?DOM 中刪除。我確信這個(gè)選擇器可以用在很多其他情況下。在 CodePen 上查看此代碼的實(shí)時(shí)版本。

    基于索引的選擇器

    除了像 :nth-child() 這樣的 CSS 選擇器之外,jQuery 也有自己的一組基于索引的選擇器。這些選擇器是 :eq(index)、:lt(index):gt(index)。與基于 CSS 的選擇器不同,這些選擇器使用從零開始的索引。這意味著 :nth-child(1) 將選擇第一個(gè)子級(jí),而 :eq(1) 將選擇第二個(gè)子級(jí)。要選擇第一個(gè)孩子,您必須使用 :eq(0)。

    這些選擇器也可以接受負(fù)值。當(dāng)指定負(fù)值時(shí),將從最后一個(gè)元素開始向后計(jì)數(shù)。

    :lt(index) 選擇索引小于指定值的所有元素。要選擇前三個(gè)元素,您將使用 :lt(3)。這是因?yàn)榍叭齻€(gè)元素的索引值分別為 0、1 和 2。使用負(fù)索引將選擇向后計(jì)數(shù)后到達(dá)的元素之前的所有值。同樣,: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
    

    嘗試單擊演示中的各個(gè)按鈕以更好地了解索引選擇器。

    表單選擇器

    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>
    

    我在這里創(chuàng)建了兩個(gè)文本元素和四個(gè)復(fù)選框。該表單非?;?,但它應(yīng)該讓您了解表單選擇器的工作原理。我們將使用 :text 選擇器計(jì)算文本元素的數(shù)量,并更新第一個(gè)文本輸入中的文本。

    var textCount = $(":text").length;
    $(".text-elements").text('Text Inputs : ' + textCount);
    
    $(":text").eq(0).val('Added programatically!');
    

    我使用 :text 選擇所有文本輸入,然后使用 length 方法來計(jì)算它們的數(shù)量。在第三條語句中,我使用前面討論的 :eq() 選擇器來訪問第一個(gè)元素,然后設(shè)置其值。

    請(qǐng)記住,從 jQuery 1.5.2 開始,對(duì)于未指定任何 type 屬性的元素,:text 返回 true。

    看看演示。

    標(biāo)頭選擇器 (:header)

    如果您想選擇網(wǎng)頁上的所有標(biāo)題元素,可以使用簡(jiǎn)短的 $(":header") 版本,而不是詳細(xì)的 $ ("h1 h2 h3 h4 h5 h6") 選擇器。此選擇器不是 CSS 規(guī)范的一部分。因此,首先使用純 CSS 選擇器,然后使用 .filter(":header") 可以獲得更好的性能。

    例如,假設(shè)網(wǎng)頁上有一個(gè) article 元素,并且它具有三個(gè)不同的標(biāo)題。現(xiàn)在,為了簡(jiǎn)潔起見,您可以使用 $("article :header") 而不是 $("article h1,article h2,article h3")。為了使其更快,您可以使用 $("article").filter(":header")。這樣您就可以兩全其美。

    要對(duì)所有標(biāo)題元素進(jìn)行編號(hào),您可以使用以下代碼。

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

    嘗試一下隨附的演示。

    最終想法

    在本教程中,我討論了使用 jQuery 時(shí)可能遇到的不常見選擇器。雖然大多數(shù)選擇器都有可供您使用的替代方案,但了解這些選擇器的存在仍然是件好事。

    我希望您在本教程中學(xué)到了一些新東西。如果您有任何問題或建議,請(qǐng)?jiān)u論。

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

    Statement of this Website
    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

    Hot AI Tools

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Hot Topics

    PHP Tutorial
    1488
    72
    How to diagnose high CPU usage caused by WordPress How to diagnose high CPU usage caused by WordPress Jul 06, 2025 am 12:08 AM

    The main reasons why WordPress causes the surge in server CPU usage include plug-in problems, inefficient database query, poor quality of theme code, or surge in traffic. 1. First, confirm whether it is a high load caused by WordPress through top, htop or control panel tools; 2. Enter troubleshooting mode to gradually enable plug-ins to troubleshoot performance bottlenecks, use QueryMonitor to analyze the plug-in execution and delete or replace inefficient plug-ins; 3. Install cache plug-ins, clean up redundant data, analyze slow query logs to optimize the database; 4. Check whether the topic has problems such as overloading content, complex queries, or lack of caching mechanisms. It is recommended to use standard topic tests to compare and optimize the code logic. Follow the above steps to check and solve the location and solve the problem one by one.

    How to minify JavaScript files in WordPress How to minify JavaScript files in WordPress Jul 07, 2025 am 01:11 AM

    Miniving JavaScript files can improve WordPress website loading speed by removing blanks, comments, and useless code. 1. Use cache plug-ins that support merge compression, such as W3TotalCache, enable and select compression mode in the "Minify" option; 2. Use a dedicated compression plug-in such as FastVelocityMinify to provide more granular control; 3. Manually compress JS files and upload them through FTP, suitable for users familiar with development tools. Note that some themes or plug-in scripts may conflict with the compression function, and you need to thoroughly test the website functions after activation.

    How to optimize WordPress without plugins How to optimize WordPress without plugins Jul 05, 2025 am 12:01 AM

    Methods to optimize WordPress sites that do not rely on plug-ins include: 1. Use lightweight themes, such as Astra or GeneratePress, to avoid pile-up themes; 2. Manually compress and merge CSS and JS files to reduce HTTP requests; 3. Optimize images before uploading, use WebP format and control file size; 4. Configure.htaccess to enable browser cache, and connect to CDN to improve static resource loading speed; 5. Limit article revisions and regularly clean database redundant data.

    How to use the Transients API for caching How to use the Transients API for caching Jul 05, 2025 am 12:05 AM

    TransientsAPI is a built-in tool in WordPress for temporarily storing automatic expiration data. Its core functions are set_transient, get_transient and delete_transient. Compared with OptionsAPI, transients supports setting time of survival (TTL), which is suitable for scenarios such as cache API request results and complex computing data. When using it, you need to pay attention to the uniqueness of key naming and namespace, cache "lazy deletion" mechanism, and the issue that may not last in the object cache environment. Typical application scenarios include reducing external request frequency, controlling code execution rhythm, and improving page loading performance.

    How to prevent comment spam programmatically How to prevent comment spam programmatically Jul 08, 2025 am 12:04 AM

    The most effective way to prevent comment spam is to automatically identify and intercept it through programmatic means. 1. Use verification code mechanisms (such as Googler CAPTCHA or hCaptcha) to effectively distinguish between humans and robots, especially suitable for public websites; 2. Set hidden fields (Honeypot technology), and use robots to automatically fill in features to identify spam comments without affecting user experience; 3. Check the blacklist of comment content keywords, filter spam information through sensitive word matching, and pay attention to avoid misjudgment; 4. Judge the frequency and source IP of comments, limit the number of submissions per unit time and establish a blacklist; 5. Use third-party anti-spam services (such as Akismet, Cloudflare) to improve identification accuracy. Can be based on the website

    How to enqueue assets for a Gutenberg block How to enqueue assets for a Gutenberg block Jul 09, 2025 am 12:14 AM

    When developing Gutenberg blocks, the correct method of enqueue assets includes: 1. Use register_block_type to specify the paths of editor_script, editor_style and style; 2. Register resources through wp_register_script and wp_register_style in functions.php or plug-in, and set the correct dependencies and versions; 3. Configure the build tool to output the appropriate module format and ensure that the path is consistent; 4. Control the loading logic of the front-end style through add_theme_support or enqueue_block_assets to ensure that the loading logic of the front-end style is ensured.

    How to add custom fields to users How to add custom fields to users Jul 06, 2025 am 12:18 AM

    To add custom user fields, you need to select the extension method according to the platform and pay attention to data verification and permission control. Common practices include: 1. Use additional tables or key-value pairs of the database to store information; 2. Add input boxes to the front end and integrate with the back end; 3. Constrain format checks and access permissions for sensitive data; 4. Update interfaces and templates to support new field display and editing, while taking into account mobile adaptation and user experience.

    How to optimize WordPress robots txt How to optimize WordPress robots txt Jul 13, 2025 am 12:37 AM

    robots.txt is crucial to the SEO of WordPress websites, and can guide search engines to crawl behavior, avoid duplicate content and improve efficiency. 1. Block system paths such as /wp-admin/ and /wp-includes/, but avoid accidentally blocking the /uploads/ directory; 2. Add Sitemap paths such as Sitemap: https://yourdomain.com/sitemap.xml to help search engines quickly discover site maps; 3. Limit /page/ and URLs with parameters to reduce crawler waste, but be careful not to block important archive pages; 4. Avoid common mistakes such as accidentally blocking the entire site, cache plug-in affecting updates, and ignoring the matching of mobile terminals and subdomains.

    See all articles