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

Use label tag to select the radio button by clicking the text

The <label> tag defines a label (tag) for an...

Detailed steps for Spring Boot packaging and uploading to Docker repository

Important note: Before studying this article, you...

Sample code for implementing the Olympic rings with pure HTML+CSS

Rendering Code - Take the blue and yellow rings a...

10 Tips to Improve Website Usability

Whether it is a corporate website, a personal blo...

Analysis of 2 Token Reasons and Sample Code in Web Project Development

Table of contents question: There are 2 tokens in...

VMware configuration VMnet8 network method steps

Table of contents 1. Introduction 2. Configuratio...

Calling Baidu Map to obtain longitude and latitude in Vue

In the project, it is necessary to obtain the lat...

Mysql date formatting and complex date range query

Table of contents Preface Query usage scenario ca...

The process of using vxe-table to make editable tables in vue

There is a table in the project that needs to be ...

Initial settings after installing Ubuntu 16 in the development environment

The office needs Ubuntu system as the Linux devel...

Detailed explanation of how to use zabbix to monitor oracle database

1. Overview Zabbix is ​​a very powerful and most ...

Various methods to implement the prompt function of text box in html

You can use the attribute in HTML5 <input="...

Why TypeScript's Enum is problematic

Table of contents What happened? When to use Cont...

Vue integrates Tencent TIM instant messaging

This article mainly introduces how to integrate T...