jQuery的.each函数只需要一个参数 – 一个函数.然而,在这段jQuery代码中,我们看到以下内容:
if ( callback ) { self.each( callback,[ responseText,status,jqXHR ] ); }
两个args被传递给.each.我假设括号中的值是回调函数的参数,但是我不清楚为什么这是可能的以及为什么有人会这样做而不是直接调用函数? :
if ( callback ) { self.each( callback(responseText,jqXHR) ); }
解决方法
“I’m not clear on why this is possible and why someone would do this…”
他们不会.它仅供内部使用:https://github.com/jquery/jquery/blob/1.6.2/src/core.js#L248-253
// Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args,but this is // only used internally.) each: function( callback,args ) { return jQuery.each( this,callback,args ); },
此行为可能随时发生变化.
要清楚,通常你对每个回调都有两个参数:
>作为第一个集合的i(属性名称或索引)
> i处的项目的值作为第二个
但有时在内部他们想要使用每个迭代器,但他们不需要这些参数,而是他们想要替换他们自己的.
这就是发生的事情.你can see here如果内部args属性被赋予了一个值,它们会对通过给定的args的集合进行稍微不同的迭代.
所以他们这样做:
callback.apply( object[ name ],args )
…代替:
callback.call( object[ name ],name,object[ name ] )
…或稍微不同但对于类似数组的集合实际上是相同的.
你可以自己测试一下:
// normal usage $('p').each(function( a,b,c ) { // will show the index,the element,and undefined for each "p" element console.log( a,c ); }); // internal usage $('p').each(function( a,c ) { // will show 1,2,3 once for every "p" element console.log( a,c ); },[ 1,3 ] );
但同样,这种行为不是供公众使用,可能会在没有警告的情况下改变.