search
HomeWeb Front-endJS TutorialIntroduction to the usage of each() in JQuery
Introduction to the usage of each() in JQueryJul 09, 2017 am 11:39 AM
jqueryInstructions


Instructions for using each() in JQuery


For jQuery objects, the each method is simply delegated: Pass the jQuery object as the first parameter to jQuery's each method. In other words: the each method provided by jQuery calls the method one by one on all the sub-elements of the object provided by parameter 1. The each() function is basically all The frameworks all provide a tool class function through which you can traverse the attribute values ​​of objects and arrays and process them. Both jQuery and jQuery objects implement this method. For jQuery objects, the each method is simply delegated: the jQuery object is passed as the first parameter to jQuery's each method. In other words: the each method provided by jQuery is All sub-elements in the object provided by parameter 1 are called one by one. The each method provided by the jQuery object calls the sub-elements inside jQuery one by one.

The effect of each function is not completely consistent depending on the type of parameters:

1. Traverse the object (with additional parameters)

The code is as follows:



$.each(Object, function(p1, p2) {    this;       //这里的this指向每次遍历中Object的当前属性值
    p1; p2;     //访问附加参数}, ['参数1', '参数2']);

2, Traverse the array(with attachment parameters)

The code is as follows:



##

$.each(Array, function(p1, p2){    this;       //这里的this指向每次遍历中Array的当前元素
    p1; p2;     //访问附加参数}, ['参数1', '参数2']);

3. Traverse objects (no additional parameters)

The code is as follows:

##

$.each(Object, function(name, value) {     this;      //this指向当前属性的值
     name;      //name表示Object当前属性的名称
     value;     //value表示Object当前属性的值});

4. Traverse the array (no additional parameters)

The code is as follows:


$.each(Array, function(i, value) {     this;      //this指向当前元素
     i;         //i表示Array当前下标
     value;     //value表示Array当前元素});

Here are some common uses of jQuery’s each method




##
 arr = ["one", "two", "three", "four" arr1 = [[1, 4, 3], [4, 6, 6], [7, 20, 90 obj = {one: 1, two: 2, three: 3, four: 4

The each function in JQuery is described in the official documentation of 1.3.2 as follows:

each(callback)

Execute a function with each matching element as the context.

means that every time the function passed in is executed, the this keyword in the function points to a different DOM element (a different matching element each time). Moreover, every time the function is executed, a numeric value representing the position of the element as the execution environment in the set of matching elements is passed to the function as a parameter (an integer starting from zero). Returning 'false' will stop the loop (just like using 'break' in a normal loop). Returns 'true' to jump to the next loop (just like using 'continue' in a normal loop).

The following callback is the
callback function
, indicating the operation that should be given when traversing the elements. Let’s look at a simple example below:
Iterate over two images and set their src attributes. Note: here this refers to the DOM object rather than the jQuery object.

<img  src="/static/imghwm/default1.png" data-src="test0.jpg" class="lazy" alt="Introduction to the usage of each() in JQuery" >/>$("img").each(function(i){ 
this.src = "test" + i + ".jpg"; 
}); 

结果:[ <img  src="/static/imghwm/default1.png" data-src="test0.jpg" class="lazy" alt="Introduction to the usage of each() in JQuery" >, <img  src="/static/imghwm/default1.png" data-src="test1.jpg" class="lazy" alt="Introduction to the usage of each() in JQuery" > ]


Of course, when traversing elements, jquery allows customized pop-ups. Please see the sample code: You can use 'return' to Break out of each() loop early.

HTML code:


The code is as follows:


##

<button>Change colors</button><span></span><p></p><p></p><p></p><p></p><p>Stop here</p><p></p><p></p><p></p>
jQuery code:


The code is as follows:


##

$("button").click(function(){
    $("p").each(function(index, domEle){
        $(domEle).css("backgroundColor", "wheat");        if ($(this).is("#stop")) {
            $("span").text("在p块为#" + index + "的地方停止。");            return false;
        }
    })
}

Or write like this:


Code As follows:



##
$("button").click(function(){
    $("p").each(function(index){
        $(this).css("backgroundColor","wheat");        if($(this).is("#stop")){
            $("span").text("在p块为#"+index+"的地方停止。");            return false;
        }
    })
}

Illustration:








#each() method specifies a function to run for each matching element.


Tip: Returning false can be used to stop the loop early.

Syntax

$(selector).each(function(index,element)) Parameter Description function(index,element) Required. Specifies the function to run for each matching element. •index - the index position of the selector

•element - the current element (you can also use the "this" selector


Example
Output the text of each li element:


code show as below:




$("button").click(function(){
    $("li").each(function(){
        alert($(this).text())
    });
});

实例 
obj 对象不是数组 
该方法同1的最大区别是:fn方法会被逐次不考虑返回值的进行进行。换句话说,obj对象的所有属性都会被fn方法进行调用,即使fn函数返回false。调用传入的参数同1类似。 

代码如下:



jQuery.each = function(obj, fn, args){    if (args) {        if (obj.length == undefined) {            for (var i in obj)
                fn.apply(obj, args);
        } else {            for (var i = 0, ol = obj.length; i <p> </p><p>需要特别注意的是each方法中fn的具体调用方法并不是采用简单的fn(i,val)或fn(args),而是采用了fn.call(val,i,val)或fn.apply(obj.args)的形式,这意味着,在你自己的fn的实现中,可以直接采用this指针引用数组或是对象的子元素。 <br><br><strong>那怎么跳出each呢</strong> <br>jquery再遍历选定的对象时候用each比较方便。有种应用是找到里面符合条件的对象后,要跳出这个循环。<br><a href="http://www.php.cn/wiki/48.html" target="_blank">javascript</a>的跳出循环一般用break. <br>同事遇到这个问题,下意识 的用了break,想跳出这个循环。结果报错 <br>SyntaxError: unlabeled break must be inside loop or switch <br>经查,应该用一个 <br>在回调函数里return false即可,大多数jq的方法都是如此的 <br></p><p class="codetitle">代码如下:</p><p class="codebody"><br>返回 'false' 将停止循环 (就像在普通的循环中使用 'break')。 <br>返回 'true' 跳至下一个循环(就像在普通的循环中使用'continue')。 </p><p> </p>

The above is the detailed content of Introduction to the usage of each() in JQuery. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
jquery实现多少秒后隐藏图片jquery实现多少秒后隐藏图片Apr 20, 2022 pm 05:33 PM

实现方法:1、用“$("img").delay(毫秒数).fadeOut()”语句,delay()设置延迟秒数;2、用“setTimeout(function(){ $("img").hide(); },毫秒值);”语句,通过定时器来延迟。

axios与jquery的区别是什么axios与jquery的区别是什么Apr 20, 2022 pm 06:18 PM

区别:1、axios是一个异步请求框架,用于封装底层的XMLHttpRequest,而jquery是一个JavaScript库,只是顺便封装了dom操作;2、axios是基于承诺对象的,可以用承诺对象中的方法,而jquery不基于承诺对象。

jquery怎么修改min-height样式jquery怎么修改min-height样式Apr 20, 2022 pm 12:19 PM

修改方法:1、用css()设置新样式,语法“$(元素).css("min-height","新值")”;2、用attr(),通过设置style属性来添加新样式,语法“$(元素).attr("style","min-height:新值")”。

jquery怎么在body中增加元素jquery怎么在body中增加元素Apr 22, 2022 am 11:13 AM

增加元素的方法:1、用append(),语法“$("body").append(新元素)”,可向body内部的末尾处增加元素;2、用prepend(),语法“$("body").prepend(新元素)”,可向body内部的开始处增加元素。

jquery怎么删除div内所有子元素jquery怎么删除div内所有子元素Apr 21, 2022 pm 07:08 PM

删除方法:1、用empty(),语法“$("div").empty();”,可删除所有子节点和内容;2、用children()和remove(),语法“$("div").children().remove();”,只删除子元素,不删除内容。

jquery中apply()方法怎么用jquery中apply()方法怎么用Apr 24, 2022 pm 05:35 PM

在jquery中,apply()方法用于改变this指向,使用另一个对象替换当前对象,是应用某一对象的一个方法,语法为“apply(thisobj,[argarray])”;参数argarray表示的是以数组的形式进行传递。

jquery怎么去掉只读属性jquery怎么去掉只读属性Apr 20, 2022 pm 07:55 PM

去掉方法:1、用“$(selector).removeAttr("readonly")”语句删除readonly属性;2、用“$(selector).attr("readonly",false)”将readonly属性的值设置为false。

jquery on()有几个参数jquery on()有几个参数Apr 21, 2022 am 11:29 AM

on()方法有4个参数:1、第一个参数不可省略,规定要从被选元素添加的一个或多个事件或命名空间;2、第二个参数可省略,规定元素的事件处理程序;3、第三个参数可省略,规定传递到函数的额外数据;4、第四个参数可省略,规定当事件发生时运行的函数。

See all articles

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),