JQuery日记 2014-04.29
时间:2014-04-29 13:26:21
收藏:0
阅读:387
JQuery原型对象(续)
Test_Html
(4).each(callback,args)
迭代JQuery对象上的元素并调用callback参数,如果某次迭代中callback返回false,停止迭代.args为callback的参数,args必须为数组.在callback中this引用的当前迭代的元素.
Test_HTML
<body>
<div id= "div1">div1</div ><div id= "div2">div2</div >
<span id= "span1">span1</span ><span id= "span2">span2</span ><span id="span3" >span3 </span>
</body>
Test_Script
$(function(){ var $div = $(‘div‘ ); var args = [":参数" ] $div.each( function(){ alert( this.id + arguments[0]); return false ; },args); //只弹出一次 div1:参 数 });
.each(callback, args)调用了JQuery的静态函数JQuery.each(obj, callback, args)
JQuery.each(obj, callback, args)的源码也比较简单,见注释 // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); //如果有参数 if ( args ) { //如果是类数组 //则用使用obj[下标]的方式访问迭代的元素 if ( isArray ) { for ( ; i < length; i++ ) { //绑定回调函数的执行作用域,即回调函数使用this时,this指向当前迭代的元素,回调函数的参数为传入的args value = callback.apply( obj[ i ], args ); //如果返回false,退出迭代 if ( value === false ) { break; } } //如果不是是类数组 //则用for-in迭代 } 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 //和上个分支的处理一样这 //只是没有传入args //大量的重复代码是为了更少的逻辑判断,匹配最长用的方式,使处理更快 } 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; } } } } //返回要迭代的obj,通常是jquery对象 return obj; },
(5) .map(callback)
迭代JQuery对象中的元素,每次迭代执行callback方法,返回callback返回值数组组成的新的JQuery对象.
Test_Html
<body>
<div id= "div1" >div1 </div >< div id= "div2" >div2 </div >
<span id= "span1" >span1 </span >< span id= "span2" >span2 </span >< span id ="span3" >span3</span>
</body>
Test_Script
var $div = $(‘div‘ ); $div.map( function (){ return this .parentNode; }).each( function (){ alert( this .tagName); //弹出两次 BODY });
map源码:
map: function( callback ) { return this .pushStack( jQuery.map( this, function ( elem, i ) { return callback.call( elem, i, elem ); })); },
.map(callback)调用$.map()根据其返回的元素数组返回一个新的JQuery对象.
$.map(elements, callback, arg)源码
map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), //存放结果的数组 ret = []; // Go through the array, translating each of the items to their new values if ( isArray ) { for ( ; i < length; i++ ) { //嗲用callback绑定执行作用域为当前迭代元素 value = callback( elems[ i ], i, arg ); if ( value != null ) { //将返回值推入数组末尾 ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return concat.apply( [], ret ); },
评论(0)