*jQuery 2 Attribute operation, text attribute value, element operation, size and position operation

1.1. jQuery attribute manipulation

​ There are three common attribute operations in jQuery: prop() / attr() / data();

1.1.1 The intrinsic property value of the element prop()

​ The so-called inherent attributes of the element are the attributes of the element itself, such as the href in the element, such as the type in the element.

grammar
Insert picture description here

​ Note: In addition to ordinary attribute operations, prop() is more suitable for operating form attributes: disabled / checked / selected, etc.

1.1.2 Element custom attribute value attr()

​ The attributes that users add to elements are called custom attributes. For example, add index = "1" to the div.

grammar

Insert picture description here

​ Note: Attr() is more suitable for operating custom attributes in addition to ordinary attribute operations. (This method can also get H5 custom attributes)

1.1.3 Data Cache data()

​ The data() method can access data on the specified element without modifying the DOM element structure. Once the page is refreshed, all previously stored data will be removed.

grammar

Insert picture description here

​ Note: At the same time, you can also read the HTML5 custom attribute data-index, and the result is a number.

Demo code

<body>
    <a href="http://www.itcast.cn" title="都挺好">都挺好</a>
    <input type="checkbox" name="" id="" checked>
    <div index="1" data-index="2">我是div</div>
    <span>123</span>
    <script>
        $(function() {
    
    
            //1. element.prop("属性名") 获取元素固有的属性值
            console.log($("a").prop("href"));
            $("a").prop("title", "我们都挺好");
            $("input").change(function() {
    
    
                console.log($(this).prop("checked"));
            });
            // console.log($("div").prop("index"));
            // 2. 元素的自定义属性 我们通过 attr()
            console.log($("div").attr("index"));
            $("div").attr("index", 4);
            console.log($("div").attr("data-index"));
            // 3. 数据缓存 data() 这个里面的数据是存放在元素的内存里面
            $("span").data("uname", "andy");
            console.log($("span").data("uname"));
            // 这个方法获取data-index h5自定义属性 第一个 不用写data-  而且返回的是数字型
            console.log($("div").data("index"));
        })
    </script>
</body>

1.1.4 Case: Shopping Cart Case Module-Select All

1. The idea of ​​selecting all: the 3 small checkbox buttons (j-checkbox) in the selected state (checked) follow the select all button (checkall).
2. Because checked is an inherent property of the check box, we need to use the prop() method to get and set this property.
3. Assign the state of the select all button to the 3 small checkboxes.
4. Every time we click the small checkbox button, we judge:
5. If the number of small checkboxes selected is equal to 3, the select all button should be selected, otherwise the select all button is not selected.
6.:checked selector:checked Find the selected form element.

​ The code implementation is omitted. (Refer to the source code for details)

1.2. jQuery text attribute value

​ There are three common operations on jQuery's text attribute value: html() / text() / val(); correspond to innerHTML, innerText and value attributes in JS respectively.

1.2.1 jQuery content text value

​ There are three common operations: html() / text() / val(); Corresponding to innerHTML, innerText and value attributes in JS, mainly for element content and form value operations.

grammar

Insert picture description here

​ Note: html() can recognize tags, text() does not recognize tags.

Demo code

<body>
    <div>
        <span>我是内容</span>
    </div>
    <input type="text" value="请输入内容">
    <script>
        // 1. 获取设置元素内容 html()
        console.log($("div").html());
        // $("div").html("123");
        // 2. 获取设置元素文本内容 text()
        console.log($("div").text());
        $("div").text("123");
        // 3. 获取设置表单值 val()
        console.log($("input").val());
        $("input").val("123");
    </script>
</body>

1.2.2. Case: Shopping Cart Case Module-Increase or Decrease the Quantity of Products

1. The core idea: first declare a variable, when we click the + sign (increment), let the value ++, and then assign it to the text box.
2. Note 1: Only the quantity of this product can be increased, which is the value of the brother text box (itxt) of the current + sign.
3. To modify the value of the form is the val() method
. 4. Note 2: The initial value of this variable should be the value of this text box, on the basis of this value ++. To get the value of the form
5. The decrement has the same idea, but if the value of the text box is 1, it cannot be decremented.

​ The code implementation is omitted. (Refer to the source code for details)

1.2.3. Case: Shopping Cart Case Module-Modified Commodity Subtotal

1. The core idea: each time you click on the + or -, the subtotal of the product is multiplied by the value of the text box by the current product price.
2. Note 1: Only the subtotal of this product can be added, which is the subtotal of the current product Module (p-sum)
3. To modify the content of common elements is the text() method
4. Note 2: For the current commodity price, remove the ¥ symbol and multiply the string substr(1)
5.parents('Selector ') can return to the specified ancestor element
6. The final calculation result if you want to keep 2 decimal places through the toFixed(2) method
7. The user can also directly modify the value in the form, and also calculate the subtotal. Use the form change event
8. Multiply the unit price by the value in the latest form, but it is still the subtotal of the current product

​ The code implementation is omitted. (Refer to the source code for details)

1.3. jQuery element operation

​ jQuery element operation mainly talks about using jQuery methods to manipulate tags such as traversing, creating, adding, and deleting operations.

1.3.1. Iterating over elements

​ jQuery implicit iteration is to do the same operation on the same type of element. If you want to perform different operations on the same type of element, you need to use traversal.

Grammar 1

Insert picture description here

​ Note: This method is used to traverse each item in the jQuery object. The element in the callback function is a DOM object. If you want to use the jQuery method, you need to convert it.

Grammar 2

Insert picture description here

​ Note: This method is used to traverse each item in the jQuery object. The element in the callback function is a DOM object. If you want to use the jQuery method, you need to convert it.

Demo code

<body>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <script>
        $(function() {
    
    
            // 如果针对于同一类元素做不同操作,需要用到遍历元素(类似for,但是比for强大)
            var sum = 0;
            var arr = ["red", "green", "blue"];
            // 1. each() 方法遍历元素 
            $("div").each(function(i, domEle) {
    
    
                // 回调函数第一个参数一定是索引号  可以自己指定索引号号名称
                // console.log(i);
                // 回调函数第二个参数一定是 dom 元素对象,也是自己命名
                // console.log(domEle);  // 使用jQuery方法需要转换 $(domEle)
                $(domEle).css("color", arr[i]);
                sum += parseInt($(domEle).text());
            })
            console.log(sum);
            // 2. $.each() 方法遍历元素 主要用于遍历数据,处理数据
            // $.each($("div"), function(i, ele) {
    
    
            //     console.log(i);
            //     console.log(ele);
            // });
            // $.each(arr, function(i, ele) {
    
    
            //     console.log(i);
            //     console.log(ele);
            // })
            $.each({
    
    
                name: "andy",
                age: 18
            }, function(i, ele) {
    
    
                console.log(i); // 输出的是 name age 属性名
                console.log(ele); // 输出的是 andy  18 属性值
            })
        })
    </script>
</body>

1.3.2. Case: Shopping Cart Case Module-Calculating Total and Total

1. Adding the values ​​in all text boxes is the total amount, and the total is the same.
2. The values ​​in the text box are different. If you want to add up, you need to traverse with each(), declare a variable as a counter, and add up.

​ The code implementation is omitted. (Refer to the source code for details)

1.3.3. Create, add, delete

​ There are many ways to create, add, and delete jQuery method operation elements, so the key to use is as follows:

Grammar sum

Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here

​ Note: The above are just common methods for creating, adding, and deleting elements. For other methods, please refer to the API.

Case code

<body>
    <ul>
        <li>原先的li</li>
    </ul>
    <div class="test">我是原先的div</div>
    <script>
        $(function() {
    
    
            // 1. 创建元素
            var li = $("<li>我是后来创建的li</li>");
      
            // 2. 添加元素
            // 	2.1 内部添加
            // $("ul").append(li);  内部添加并且放到内容的最后面 
            $("ul").prepend(li); // 内部添加并且放到内容的最前面
            //  2.2 外部添加
            var div = $("<div>我是后妈生的</div>");
            // $(".test").after(div);
            $(".test").before(div);
      
            // 3. 删除元素
            // $("ul").remove(); 可以删除匹配的元素 自杀
            // $("ul").empty(); // 可以删除匹配的元素里面的子节点 孩子
            $("ul").html(""); // 可以删除匹配的元素里面的子节点 孩子
        })
    </script>
</body>

1.3.4 Case: Shopping Cart Case Module-Delete Commodity Module

1. The core idea: delete the element of the product remove()
2. There are three places that need to be deleted: 1. The delete button behind the product 2. Delete the selected product 3. Clean the shopping cart
3. The delete button behind the product: must be Delete the current product, so start from $(this)
4. Delete the selected product: First determine whether the small check box button is selected, if it is selected, delete the corresponding product
5. Clean the shopping cart: It is to remove all Delete all products

​ The code implementation is omitted. (Refer to the source code for details)

1.3.5 Case: Shopping cart case module-add background to selected product

1. The core idea: add background to the selected product, uncheck to remove the background
. 2. Click on the select all button: if the select all is selected, then all the products add the background, otherwise remove the background
3. Small check box Click: If it is selected, add background to current product, otherwise remove background
4. This background can be modified by class name, add class and delete class

​ The code implementation is omitted. (Refer to the source code for details)

1.4. jQuery size, position operation

​ jQuery provides us with two sets of APIs for quickly obtaining and setting element size and position, which are convenient and easy to use. The content is as follows.

1.4.1. jQuery size operation

​ jQuery size operations include the acquisition and setting of element width and height, and different APIs correspond to different box models.

grammar

Insert picture description here

Code demo

<body>
    <div></div>
    <script>
        $(function() {
    
    
            // 1. width() / height() 获取设置元素 width和height大小 
            console.log($("div").width());
            // $("div").width(300);

            // 2. innerWidth() / innerHeight()  获取设置元素 width和height + padding 大小 
            console.log($("div").innerWidth());

            // 3. outerWidth()  / outerHeight()  获取设置元素 width和height + padding + border 大小 
            console.log($("div").outerWidth());

            // 4. outerWidth(true) / outerHeight(true) 获取设置 width和height + padding + border + margin
            console.log($("div").outerWidth(true));
        })
    </script>
</body>

​ Note: With this set of APIs, we will be able to quickly obtain the width and height of the child. As for other properties to be obtained and set, we must use css() and other methods to cooperate.

1.4.2. jQuery Position Operation

​ There are three main position operations of jQuery: offset(), position(), scrollTop()/scrollLeft(), the details are as follows:

grammar

Insert picture description here
Insert picture description here
Insert picture description here

Code demo

<body>
    <div class="father">
        <div class="son"></div>
    </div>
        
    <div class="back">返回顶部</div>
    <div class="container"></div>
   
    <script>
        $(function() {
    
    
            // 1. 获取设置距离文档的位置(偏移) offset
            console.log($(".son").offset());
            console.log($(".son").offset().top);
            // $(".son").offset({
    
    
            //     top: 200,
            //     left: 200
            // });
      
            // 2. 获取距离带有定位父级位置(偏移) position   如果没有带有定位的父级,则以文档为准
            // 这个方法只能获取不能设置偏移
            console.log($(".son").position());
            // $(".son").position({
    
    
            //     top: 200,
            //     left: 200
            // });
      
      		// 3. 被卷去的头部
      		$(document).scrollTop(100);
            // 被卷去的头部 scrollTop()  / 被卷去的左侧 scrollLeft()
            // 页面滚动事件
            var boxTop = $(".container").offset().top;
            $(window).scroll(function() {
    
    
                // console.log(11);
                console.log($(document).scrollTop());
                if ($(document).scrollTop() >= boxTop) {
    
    
                    $(".back").fadeIn();
                } else {
    
    
                    $(".back").fadeOut();
                }
            });
            // 返回顶部
            $(".back").click(function() {
    
    
                // $(document).scrollTop(0);
                $("body, html").stop().animate({
    
    
                    scrollTop: 0
                });
                // $(document).stop().animate({
    
    
                //     scrollTop: 0
                // }); 不能是文档而是 html和body元素做动画
            })
        })
    </script>
</body>

1.4.3. Case: Back to top with animation

1. Core principle: Use animate animation to return to the top.
2. There is a scrollTop property in the animate animation function, you can set the position
3. But the element is animated, so $("body,html").animate({scrollTop: 0})

​ The code implementation is omitted. (Refer to the source code for details)

1.4.4. Case: Pinyougo Elevator Navigation (Part 1)

1. When we scroll to the recommended module of today, let the elevator navigation display
2. Click on the elevator navigation page to scroll to the corresponding content area
3. Core algorithm: because the elevator navigation module and the content area module correspond to each other
4. When we click If you navigate a small module in the elevator, you can get the index number of the current small module
5. You can find the distance the animate will move: the offset().top of the current index number content area module
6. Then execute the animation.

​ The code implementation is omitted. (Refer to the source code for details)

1.4.5. Case: Pinyougo Elevator Navigation (Part 2)

1. When we click on a small li in the elevator navigation, the current small li adds the current class, and the brother removes the class name
. 2. When we scroll to a certain module in the content area, the elevator navigation on the left, the corresponding small li module, is also The current class will be added, and the brothers will remove the current class.
3. The triggered event is page scrolling, so this function should be written into the page scrolling event.
4. You need to use each to traverse large modules in the content area. Each module element and index number in the content area can be obtained in each
5. Judgment condition: The head being rolled is greater than or equal to the offset().top of each module in the content area
6. Use this index number to find the corresponding Add a class to the elevator navigation small li.

​ The code implementation is omitted. (Refer to the source code for details)

1.5. Today's Summary

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_48116269/article/details/108083378