深入学习jquery源码之each()

$.each()

遍历一个数组或对象,可以是DOM、json等格式,等价于for循环

返回值:jQuery.each(callback) 

参数:对于每个匹配的元素所要执行的函数

概述:

以每一个匹配的元素作为上下文来执行一个函数。

意味着,每次执行传递进来的函数时,函数中的this关键字都指向一个不同的DOM元素(每次都是一个不同的匹配元素)。而且,在每次执行函数时,都会给函数传递一个表示作为执行环境的元素在匹配的元素集合中所处位置的数字值作为参数(从零开始的整型)。 返回 'false' 将停止循环 (就像在普通的循环中使用 'break')。返回 'true' 跳至下一个循环(就像在普通的循环中使用'continue')。

使用:

迭代两个图像,并设置它们的 src 属性。注意:此处 this 指代的是 DOM 对象而非 jQuery 对象。

$("img").each(function(i){
   this.src = "test" + i + ".jpg";
 });

结果

[ <img src="test0.jpg" />, <img src="test1.jpg" /> ]
 var arr1=['aa','bb','cc','dd'];
 $.each(arr1,function(i,val){ 
 console.log(i+'```````'+val);
 }
$("input:hidden").each(function(i,val){  //第一个参数表示索引下标,第二个参数表示当前索引元素
    alert(i);
    alert(val.name);
    alert(val.value);       
});

如果你想得到 jQuery对象,可以使用 $(this) 函数。

$("img").each(function(){
  $(this).toggleClass("example");
});
$('td[aria="View_CHECK_NAME"]').each(function(){
	if($(this).html()=="yes"){
		$(this).attr("style","color:red; text-align:center;cursor:pointer");
	}
})

输出每个 li 元素的文本:

$("button").click(function(){
  $("li").each(function(){
    alert($(this).text())
  });
});
  $("#ty").click(function(){
		var cancelId = "";
                var Name=""
		$("#RecList").next().find("[type='checkbox']").each(function(index,item){
				var cancelTd =  $("#RecList").next().find("tr").eq(index).find("td");
				cancelId += (cancelTd.eq(1).text()+",");
                                Name+= (cancelTd.eq(2).text()+",");
		});
		cancelId = cancelId.substring(1,cancelId.length-1);
		cancelId = cancelId.substring(0,cancelId.length-1);
		if(cancelId == ""){
			layer.msg("");
                return false;
		}
             $.ajax({
			type : "post",
			url : CONTEXT_PATH + '/update',
			data : {"cancelId " : cancelId,"Name":Name},
			success : function(data){
				
				if(data > 0){
					$("button[name='comQue']").each(function(index,item){
						$(this).trigger("click");
		})
			
		
  })

遍历二维数组

两个参数,第一个参数表示下标,第二个参数表示一维数组中的每一个数组

var arr2=[['aaa','bbb'],['ccc','ddd'],['eee','fff']];
$.each(arr2,function(i,item){ 
 console.log(i+'````'+item);
}
$(function () {
            $.each([["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]], function (i, el) {
                console.log(i+ ":" + el);
                //输出0:a,b,c  1:d,e,f  2:g,h,i   这时的i为数组下标,el相当于取这二维数组中的每一个数组
                $.each(el, function (index, itemobj) {
                    console.log(index + ":" + itemobj);
                });
            });
            //输出0.:a,b,c  0:a 1:b 2:c  1:d,e,f  0:d 1:e 2:f  2:g,h,i 0:g 1:h 2:i
        });

遍历json

var json1={key1:'a',key2:'b',key3:'c'};
 $.each(json1,function(key,value){  //遍历键值对
            console.log(key+'````'+value);
  })
$(function () {
            var json = [{ name: "小明", sex: "男" }, { name: "小糖", sex: "女" }, { name: "小孩", sex: "男"}];  //自定义一个json数组
            $.each(json, function (index, obj) {
                console.log(index + ":" + obj.name+":"+obj.sex);
            });
        });

输出:0:小明:男 1:小糖:女 2:小孩:男

二维数组有json对象

var arr3=[{name:'n1',age:18},{name:'n2',age:20},{name:'n3',age:22}];
        $.each(arr3,function(i,val){
            console.log(i+'`````'+val);   
    //输出
    /* 0`````[object Object] 1`````[object Object] i2`````[object Object]*/
            console.log(val.name); //获取每一个json里面的name值
            console.log(val["name"]);
            $.each(val,function(key,val2){
                console.log(key+'```'+val2);
            })
        });

你可以使用 'return' 来提前跳出 each() 循环。

<button>Change colors</button>
<span></span> 
<div></div> 
<div></div>

<div></div> 
<div></div>
<div id="stop">Stop here</div> 
<div></div>

<div></div>
<div></div>
$("button").click(function () { 
$("div").each(function (index, domEle) { 
  // domEle == this 
  $(domEle).css("backgroundColor", "yellow");  
  if ($(this).is("#stop")) { 
  $("span").text("Stopped at div index #" + index); 
  return false; 
  } 
});
});

forEach方法中的function回调有三个参数:第一个参数是遍历的数组内容,第二个参数是对应的数组索引,第三个参数是数组本身

var arr = [1,2,3,4];
arr.forEach(function(value,index,array){
    array[index] == value;    //结果为true
    sum+=value;  
    });
console.log(sum);    //结果为 10

方法等价于:

$.each([],function(index,value,array){
 
   //code something
 
 })

jquery的each()源码实现

(function (global, factory) {

    if (typeof module === "object" && typeof module.exports === "object") {
        module.exports = global.document ?
            factory(global, true) :
            function (w) {
                if (!w.document) {
                    throw new Error("jQuery requires a window with a document");
                }
                return factory(w);
            };
    } else {
        factory(global);
    }

}(typeof window !== "undefined" ? window : this, function (window, noGlobal) {

    var version = "1.11.3",

        // Define a local copy of jQuery
        jQuery = function (selector, context) {
            // The jQuery object is actually just the init constructor 'enhanced'
            // Need init if jQuery is called (just allow error to be thrown if not included)
            return new jQuery.fn.init(selector, context);
        }

    jQuery.fn = jQuery.prototype = {
        // The current version of jQuery being used
        jquery: version,

        constructor: jQuery,

        // Start with an empty selector
        selector: "",

        // The default length of a jQuery object is 0
        length: 0,
        each: function (callback, args) {
            return jQuery.each(this, callback, args);
        }
 };


jQuery.extend({
 each: function (obj, callback, args) {
            var value,
                i = 0,
                length = obj.length,
                isArray = isArraylike(obj);

            if (args) {
                if (isArray) {
                    for (; i < length; i++) {
                        value = callback.apply(obj[i], args);

                        if (value === false) {
                            break;
                        }
                    }
                } else {
                    for (i in obj) {
                        value = callback.apply(obj[i], args);

                        if (value === false) {
                            break;
                        }
                    }
                }

                // A special, fast, case for the most common use of each
            } else {
                if (isArray) {
                    for (; i < length; i++) {
                        value = callback.call(obj[i], i, obj[i]);

                        if (value === false) {
                            break;
                        }
                    }
                } else {
                    for (i in obj) {
                        value = callback.call(obj[i], i, obj[i]);

                        if (value === false) {
                            break;
                        }
                    }
                }
            }

            return obj;
        }
});


    function isArraylike(obj) {

        // Support: iOS 8.2 (not reproducible in simulator)
        // `in` check used to prevent JIT error (gh-2145)
        // hasOwn isn't used here due to false negatives
        // regarding Nodelist length in IE
        var length = "length" in obj && obj.length,
            type = jQuery.type(obj);

        if (type === "function" || jQuery.isWindow(obj)) {
            return false;
        }

        if (obj.nodeType === 1 && length) {
            return true;
        }

        return type === "array" || length === 0 ||
            typeof length === "number" && length > 0 && (length - 1) in obj;
    }


    jQuery.noConflict = function (deep) {
        if (window.$ === jQuery) {
            window.$ = _$;
        }

        if (deep && window.jQuery === jQuery) {
            window.jQuery = _jQuery;
        }

        return jQuery;
    };

    if (typeof noGlobal === strundefined) {
        window.jQuery = window.$ = jQuery;
    }

    return jQuery;

}));

猜你喜欢

转载自blog.csdn.net/qq_35029061/article/details/85192942