Home  >  Article  >  Web Front-end  >  A brief discussion on the traversal function in jQuery

A brief discussion on the traversal function in jQuery

青灯夜游
青灯夜游forward
2021-01-20 16:08:542001browse

This article will take you to understand the traversal function in jQuery. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

A brief discussion on the traversal function in jQuery

Recommended tutorial: jq tutorial

jQuery traversal function

jQuery traversal function includes filtering, Methods for finding and concatenating elements.

Function Description
.add() Adds an element to the match in a collection of elements.
.andSelf() Add the previous set of elements in the stack to the current set.
.children() Get all child elements of each element in the matching element set.
.closest() Start from the element itself, match the upper elements step by step, and return the first matched ancestor element.
.contents() Get the child elements of each element in the matching element collection, including text and comment nodes.
.each() Iterates over the jQuery object, executing the function for each matching element.
.end() End the most recent filtering operation in the current chain and return the set of matching elements to the previous state.
.eq() Reduces the set of matching elements to new elements at the specified index.
.filter() Reduces the set of matching elements to new elements matching the selector or matching function return value.
.find() Get the descendants of each element in the current matching element set, filtered by the selector.
.first() Reduces the set of matching elements to the first element in the set.
.has() Reduces the set of matching elements to a set containing the descendants of a specific element.
.is() Checks the current set of matching elements based on the selector, and returns true if there is at least one matching element.
.last() Reduces the set of matching elements to the last element in the set.
.map() Pass each element in the current matching set to the function and generate a new jQuery object containing the return value.
.next() Get the sibling elements immediately adjacent to each element in the matching element set.
.nextAll() Get all sibling elements after each element in the matching element set, filtered by the selector (optional).
.nextUntil() Get all sibling elements after each element until an element matching the selector is encountered.
.not() Remove elements from the set of matching elements.
.offsetParent() Get the first parent element used for positioning.
.parent() Get the parent element of each element in the current set of matching elements, filtered by the selector (optional).
.parents() Get the ancestor elements of each element in the current matching element set, filtered by the selector (optional).
.parentsUntil() Get the ancestor elements of each element in the current set of matching elements until an element matching the selector is encountered.
.prev() Get the immediately preceding sibling element of each element in the matching element set, filtered by the selector (optional).
.prevAll() Get all sibling elements before each element in the matching element set, filtered by the selector (optional).
.prevUntil() Get all sibling elements before each element until an element matching the selector is encountered.
.siblings() Get the sibling elements of all elements in the matching element set, filtered by the selector (optional).
.slice() Reduce the set of matching elements to a subset of the specified range.

Usage of each

1. Each in the array

复制代码

 var arr = [ "one", "two", "three", "four"];     
 $.each(arr, function(){     
    alert(this);     
 });   
//上面这个each输出的结果分别为:one,two,three,four    
    
var arr1 = [[1, 4, 3], [4, 6, 6], [7, 20, 9]]     
$.each(arr1, function(i, item){     
   alert(item[0]);     
});     
//其实arr1为一个二维数组,item相当于取每一个一维数组,   
//item[0]相对于取每一个一维数组里的第一个值   
//所以上面这个each输出分别为:1   4   7     
  
  
var obj = { one:1, two:2, three:3, four:4};     
$.each(obj, function(i) {     
    alert(obj[i]);           
});   
//这个each就有更厉害了,能循环每一个属性     
//输出结果为:1   2  3  4

2 .Traverse the Dom element

<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $("li").each(function(){
      alert($(this).text())
    });
  });
});
</script>
</head>
<body>
<button>输出每个列表项的值</button>
<ul>
<li>Coffee</li>
<li>Milk</li>
<li>Soda</li>
</ul>
</body>
</html>

and pop up Coffee, Milk, and Soda in turn

## 3. Comparison between each and map

The following example is to obtain the ID value of each multi-box;

each method:

Definition An empty array, add the ID value to the array through the each method; finally, after converting the array into a string, alert the value;

$(function(){
    var arr = [];
    $(":checkbox").each(function(index){
        arr.push(this.id);
    });
    var str = arr.join(",");
    alert(str);
})

map method:

Execute each :checkbox to return this.id; and automatically save these return values ​​as jQuery objects, then use the get method to convert them into native Javascript arrays, and then use the join method to convert them into strings. Finally, alert this value;

$(function(){
    var str = $(":checkbox").map(function() {
        return this.id;
    }).get().join();    
    alert(str);
})

When you need an array of values, use the map method, which is very convenient.

4. Use each

in jquery to traverse the array, using both element index and content. (i is the index, n is the content)

The code is as follows:

$.each( [0,1,2], function(i, n){
alert( "Item #" + i + ": " + n );
});

Example the object, using both member names and variable contents. (i is the member name, n is the variable content)

The code is as follows:

$.each( { name: "John", lang: "JS" }, function(i, n){
alert( "Name: " + i + ", Value: " + n );
});

Example of traversing the dom element, here an input form element is used as an example.

If you have a piece of code like this in your dom


<input name="aaa" type="hidden" value="111" /> 
<input name="bbb" type="hidden" value="222" /> 
<input name="ccc" type="hidden" value="333" /> 
<input name="ddd" type="hidden" value="444"/>

Then you use each as follows


The code is as follows:

$.each($("input:hidden"), function(i,val){
alert(val); //输出[object HTMLInputElement],因为它是一个表单元素。
alert(i); //输出索引为0,1,2,3
alert(val.name); //输出name的值
alert(val.value); //输出value的值
});

5.Find elements based on this in each

To achieve the effect, the word "reply" is only displayed when the mouse passes over it

<ol class="commentlist">
    <li class="comment">
        <div class="comment-body">
          <p>嗨,第一层评论</p>
          <div class="reply">
            <a href="#" class=".comment-reply-link">回复</a>
          </div>
        </div>
        <ul class="children">
          <li class="comment">
            <div class="comment-body">
            <p>第二层评论</p>
            <div class="reply">
              <a href="#" class=".comment-reply-link">回复</a>
            </div>
          </div></li>
        </ul>
    </li>
</ol>

js The code is as follows

$("div.reply").hover(function(){
  $(this).find(".comment-reply-link").show();
},function(){
  $(this).find(".comment-reply-link").hide();
});
To achieve the effect, verify whether all judgment questions have choices

html

<ul id="ulSingle">
    
            <li class="liStyle">
                1.  阿斯顿按时<label id="selectTips" style="display: none" class="fillTims">请选择</label>
                <!--begin选项-->
                <ul>
                    
                            <li class="liStyle2">
                                <span id="repSingle_repSingleChoices_0_labOption_0">A         </span>.阿萨德发<input type="hidden" name="repSingle$ctl00$repSingleChoices$ctl00$hidID" id="repSingle_repSingleChoices_0_hidID_0" value="1" />
                                <input id="repSingle_repSingleChoices_0_cheSingleChoice_0" type="checkbox" name="repSingle$ctl00$repSingleChoices$ctl00$cheSingleChoice" /></li>
                        
                            <li class="liStyle2">
                                <span id="repSingle_repSingleChoices_0_labOption_1">B         </span>.阿萨德发<input type="hidden" name="repSingle$ctl00$repSingleChoices$ctl01$hidID" id="repSingle_repSingleChoices_0_hidID_1" value="2" />
                                <input id="repSingle_repSingleChoices_0_cheSingleChoice_1" type="checkbox" name="repSingle$ctl00$repSingleChoices$ctl01$cheSingleChoice" /></li>
                        
                            <li class="liStyle2">
                                <span id="repSingle_repSingleChoices_0_labOption_2">C         </span>.阿斯顿<input type="hidden" name="repSingle$ctl00$repSingleChoices$ctl02$hidID" id="repSingle_repSingleChoices_0_hidID_2" value="3" />
                                <input id="repSingle_repSingleChoices_0_cheSingleChoice_2" type="checkbox" name="repSingle$ctl00$repSingleChoices$ctl02$cheSingleChoice" /></li>
                        
                </ul>
                <!--end选项-->
                <br />
            </li>
        
</ul>

js code

//验证单选题是否选中
        $("ul#ulSingle>li.liStyle").each(function (index) {
            //选项个数
            var count = $(this).find("ul>li>:checkbox").length;
            var selectedCount = 0
            for (var i = 0; i < count; i++) {
                if ($(this).find("ul>li>:checkbox:eq(" + i + ")").attr("checked")) {
                    selectedCount++;
                    break;
                }
            }
            if (selectedCount == 0) {
                $(this).find("label#selectTips").show();
                return false;
            }
            else {
                $(this).find("label#selectTips").hide();
            }
        })

ps: The legendary attr("property ", "value"); If it doesn't work in some browsers, you can use prop. If you just want to judge, you can use $(this).find("ul>li>:checkbox:eq(" i ")").is(" :checked");

6.Official explanationThe following is the official explanation:

jQuery.each(object, [callback])

Overview

General enumeration method, can be used to enumerate objects and arrays.


Unlike the $().each() method that iterates over jQuery objects, this method can be used to iterate over any object. The callback function has two parameters: the first is the member of the object or the index of the array, and the second is the corresponding variable or content. If you need to exit the each loop, you can make the callback function return false, and other return values ​​will be ignored.

Parameters

objectObject: The object or array that needs to be traversed.

callback (optional) Function: callback function executed by each member/element.


For more programming related knowledge, please visit:

Programming Video! !

The above is the detailed content of A brief discussion on the traversal function in jQuery. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete