Home Web Front-end JS Tutorial Detailed explanation of jQuery traversal function_jquery

Detailed explanation of jQuery traversal function_jquery

May 16, 2016 pm 03:51 PM
jquery

jQuery traversal functions include methods for filtering, finding, and concatenating elements.

函数 描述
.add() 将元素添加到匹配元素的集合中。
.andSelf() 把堆栈中之前的元素集添加到当前集合中。
.children() 获得匹配元素集合中每个元素的所有子元素。
.closest() 从元素本身开始,逐级向上级元素匹配,并返回最先匹配的祖先元素。
.contents() 获得匹配元素集合中每个元素的子元素,包括文本和注释节点。
.each() 对 jQuery 对象进行迭代,为每个匹配元素执行函数。
.end() 结束当前链中最近的一次筛选操作,并将匹配元素集合返回到前一次的状态。
.eq() 将匹配元素集合缩减为位于指定索引的新元素。
.filter() 将匹配元素集合缩减为匹配选择器或匹配函数返回值的新元素。
.find() 获得当前匹配元素集合中每个元素的后代,由选择器进行筛选。
.first() 将匹配元素集合缩减为集合中的第一个元素。
.has() 将匹配元素集合缩减为包含特定元素的后代的集合。
.is() 根据选择器检查当前匹配元素集合,如果存在至少一个匹配元素,则返回 true。
.last() 将匹配元素集合缩减为集合中的最后一个元素。
.map() 把当前匹配集合中的每个元素传递给函数,产生包含返回值的新 jQuery 对象。
.next() 获得匹配元素集合中每个元素紧邻的同辈元素。
.nextAll() 获得匹配元素集合中每个元素之后的所有同辈元素,由选择器进行筛选(可选)。
.nextUntil() 获得每个元素之后所有的同辈元素,直到遇到匹配选择器的元素为止。
.not() 从匹配元素集合中删除元素。
.offsetParent() 获得用于定位的第一个父元素。
.parent() 获得当前匹配元素集合中每个元素的父元素,由选择器筛选(可选)。
.parents() 获得当前匹配元素集合中每个元素的祖先元素,由选择器筛选(可选)。
.parentsUntil() 获得当前匹配元素集合中每个元素的祖先元素,直到遇到匹配选择器的元素为止。
.prev() 获得匹配元素集合中每个元素紧邻的前一个同辈元素,由选择器筛选(可选)。
.prevAll() 获得匹配元素集合中每个元素之前的所有同辈元素,由选择器进行筛选(可选)。
.prevUntil() 获得每个元素之前所有的同辈元素,直到遇到匹配选择器的元素为止。
.siblings() 获得匹配元素集合中所有元素的同辈元素,由选择器筛选(可选)。
.slice() 将匹配元素集合缩减为指定范围的子集。
Copy after login

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 
Copy after login

2. Traverse Dom elements

<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>
Copy after login

Coffee, Milk, and Soda pop up in sequence

3. Comparison between each and map

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

each method:

Define an empty array and add ID values ​​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);
})
Copy after login

map method:

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

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

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

4. Use each

in jquery

Loop through an 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 );
}); 
Copy after login

Iterate over 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 );
}); 
Copy after login

Example the DOM elements, taking an input form element 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"/> 
Copy after login

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的值
}); 
Copy after login

Find elements based on this in 5.each

To achieve the effect, the word "Reply" will only be 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>
Copy after login

The js code is as follows

$("div.reply").hover(function(){
 $(this).find(".comment-reply-link").show();
},function(){
 $(this).find(".comment-reply-link").hide();
});
Copy after login

Achieve the effect and verify whether all judgment questions have options

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>
Copy after login

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


Copy after login

6.Official explanation

The following is the official explanation:

jQuery.each(object, [callback])

Overview
A general iteration method that can be used to iterate 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 to be traversed.

callback (optional)Function
Callback function executed for each member/element.

The above is the entire content of this article, I hope you all like it.

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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Detailed explanation of jQuery reference methods: Quick start guide Detailed explanation of jQuery reference methods: Quick start guide Feb 27, 2024 pm 06:45 PM

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

In-depth analysis: jQuery's advantages and disadvantages In-depth analysis: jQuery's advantages and disadvantages Feb 27, 2024 pm 05:18 PM

jQuery is a fast, small, feature-rich JavaScript library widely used in front-end development. Since its release in 2006, jQuery has become one of the tools of choice for many developers, but in practical applications, it also has some advantages and disadvantages. This article will deeply analyze the advantages and disadvantages of jQuery and illustrate it with specific code examples. Advantages: 1. Concise syntax jQuery's syntax design is concise and clear, which can greatly improve the readability and writing efficiency of the code. for example,

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

See all articles