Detailed example of jQuery's chain programming style

Detailed example of jQuery's chain programming style

The implementation principle of chain programming

jQuery allows us developers to always use dot syntax to call our own methods. The main reason is that jQuery uses js objects internally to implement it.

In jQuery, if you keep operating on the same element or other related elements (sibling elements, parent-child elements), you can use the . syntax (dot syntax) and keep writing.

$("#box").css("background", "pink").css("font-size":"29px");
$("#box").siblings().css("background", "");

can be written as:

$("#box").css("background", "pink").siblings().css("background", "red");

To implement chain programming, the jQuery selector itself is a jQuery object. jQuery uses this internally to return itself.

    //In js, declare an object var obj = {  
         name:"Name", 
        desc: function(){   
        console.log(this); // Print the current object console.log(this.name); // Call the property of the object return this; // The principle of chain programming is that after calling the method, the method itself returns the object.
},  
      read: function(){  
        console.log("hello!");    
        return this; 
    }}


jQuery's chain programming style example

First, I will use a case to demonstrate jQuery's chain programming style. First write a page to display a list. The code is as follows:

<body>
    <div>
        <ul class="menu">
            <li class="level1">
                <a href="#">Fruit</a>
                <ul class="level2">
                    <li><a href="#">Apple</a></li>
                    <li><a href="#">Pineapple</a></li>
                    <li><a href="#">Cantaloupe</a></li>
                </ul>
            </li>
            <li class="level1">
                <a href="#">Staple Food</a>
                <ul class="level2">
                    <li><a href="#">Noodles</a></li>
                    <li><a href="#">Mantou</a></li>
                    <li><a href="#">Rice</a></li>
                </ul>
            </li>
        </ul>
    </div>
</body>

<script type="text/javascript">
    $(function() {
        $(".level1 > a").click(function() {
            $(this).addClass("current").next().show().parent.siblings().children("a").removeClass("current").next().hide();
            return false;
        });
    });
</script>

The effect after the code is executed is shown in the figure below:

The expansion effect of the above code is achieved through jQuery's chain operation. All operations of adding the current class, method calls for querying child elements, and calls to animation methods are performed on the same element. Therefore, after obtaining a jQuery object, all subsequent method and attribute calls are called continuously through ".". This mode is a chain operation.

In order to increase the readability and maintainability of the code, we modify the above chain code format as follows:

<script type="text/javascript">
    $(function() {
        $(".level1 > a").click(function() {
            // Add the current style to the current element $(this).addClass("current")
                // The next element is displayed.next().show()
                // Remove the current style from the child element a of the parent element's sibling element.parent.siblings().children("a").removeClass("current")
                // Their next element is hidden.next().hide();
            return false;
        });
    });
</script>

After adjusting the standard format, the code is easier to read and more convenient for subsequent maintenance.

At the same time, when we perform chain operations on the same jQuery object, we mainly follow the following three format specifications.

(1) For no more than three operations on the same object, they can be written directly in one line. The code is as follows:

<script type="text/javascript">
    $(function() {
        $("li").show().unbind("click");
    });
</script>

(2) For multiple operations on the same object, it is recommended to write one operation per line. The code is as follows:

<script type="text/javascript">
    $(function() {
        $(this).removeClass("mouseout")
            .addClass("mouseover")
            .stop()
            .fadeTo("fast", 0.5)
            .fadeTo("fast", 1)
            .unbind("click")
            .click(function() {
                .......
            });
    });
</script>

(3) For a small number of operations on multiple objects, you can write one line for each object. If sub-elements are involved, consider appropriate indentation. The code is as follows:

<script type="text/javascript">
    $(function() {
        $(this).addClass("highLight")
            .children("a").show().end()
            .siblings().removeClass("highLight")
            .children("a").hide();
    });
</script>

The above is about jQuery's chain programming style.

Summarize

This is the end of this article about jQuery chain programming style. For more relevant jQuery chain programming content, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Use JavaScript chain programming to simulate Jquery functions

<<:  Analysis of the Poor Performance Caused by Large Offset of LIMIT in MySQL Query

>>:  Detailed explanation of the installation process of Jenkins on CentOS 7

Recommend

Detailed explanation of JavaScript primitive data type Symbol

Table of contents Introduction Description Naming...

Build a Docker private warehouse (self-signed method)

In order to centrally manage the images we create...

Linux parted disk partition implementation steps analysis

Compared with fdisk, parted is less used and is m...

How to use Nginx proxy to surf the Internet

I usually use nginx as a reverse proxy for tomcat...

Two ways to connect WeChat mini program to Tencent Maps

I've been writing a WeChat applet recently an...

How to mount a new disk on a Linux cloud server

background A new server was added in the company,...

Several common methods of sending requests using axios in React

Table of contents Install and introduce axios dep...

How to make your browser talk with JavaScript

Table of contents 1. The simplest example 2. Cust...

Detailed Introduction to the MySQL Keyword Distinct

Introduction to the usage of MySQL keyword Distin...

Detailed explanation of how to write mysql not equal to null and equal to null

1. Table structure 2. Table data 3. The query tea...

Pure js to achieve typewriter effect

This article example shares the specific code of ...

js implements table drag options

This article example shares the specific code of ...

Implementation of Docker deployment of SQL Server 2019 Always On cluster

Table of contents Docker deployment Always on clu...