首页 > 编程语言 >深入学习jquery源码之each()

深入学习jquery源码之each()

时间:2023-02-23 22:08:44浏览次数:30  
标签:jquery function obj value length 源码 each jQuery


$.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;

}));

 

 

 

 

 

 

 

 

标签:jquery,function,obj,value,length,源码,each,jQuery
From: https://blog.51cto.com/u_11837698/6081918

相关文章

  • 深入学习jquery源码之trigger()与triggerHandler()
    深入学习jquery源码之trigger()与triggerHandler()trigger(type,[data])概述:在每一个匹配的元素上触发某类事件。这个函数也会导致浏览器同名的默认行为的执行。比如,如果用......
  • 深入学习jquery源码之map()
    概述将一组元素转换成其他数组(不论是否是元素数组)你可以用这个函数来建立一个列表,不论是值、属性还是CSS样式,或者其他特别形式。这都可以用'$.map()'来方便的建立。参数call......
  • 深入学习jquery源码之插件机制(二)
    高级插件概念链接提供对默认插件设置的公共访问我们可以而且应该对上面的代码做出的改进并公开默认的插件设置。这很重要,因为它使插件用户很容易用最少的代码覆盖/自定义......
  • 深入学习jquery源码之jQuery的二次开发
    深入学习jquery源码之jQuery的二次开发jquery.js的设计与实现(function(global,factory){if(typeofmodule==="object"&&typeofmodule.exports==="object")......
  • 深入学习jquery源码之merge()和unique()
    深入学习jquery源码之merge()概述:合并两个数组到第一个数组上。返回的结果会修改第一个数组的内容——第一个数组的元素后面跟着第二个数组的元素。要去除重复项,请使用$.uni......
  • 深入学习jquery源码之show()和hide()
    jQueryshow([speed,[easing],[fn]])概述:显示隐藏的匹配元素。这个就是'show(speed,[callback])'无动画的版本。如果选择的元素是可见的,这个方法将不会改变任何东西。......
  • 深入学习jquery源码之继承框架的实现
    深入学习jquery源码之继承框架的实现继承框架的实现实现自己的extend方法/*SimpleJavaScriptInheritance*ByJohnResighttp://ejohn.org/*MITLicensed.*///Insp......
  • 深入学习jquery源码之创建科学、复用率高的对象
    常规创建对象的方式通过{},[]来定义数组和对象1.{}大括号,表示定义一个对象,大部分情况下要有成对的属性和值,或是函数。2.[]中括号,表示一个数组,也可以理解为一个数组对象......
  • 深入学习jquery源码之原型链
    深入学习jquery源码之原型链prototype原型,对该函数对象的对象原型的引用,是函数对象的默认属性我们在定义函数的时候,函数定义的时候函数本身就会默认有一个prototype的属性,而......
  • 深入学习jquery源码之继承方案的选择
    prototype实现继承原型链继承的主要思想是:让子类型的引用指向父类型的实例。每次在函数(类)中定义了成员方法,都会导致实例有副本,因此可以借助prototype原型,进行改进先访问自己......