雖然這個例子可能不相關的答案,但因爲這個問題是如何參數每個功能傳遞給jQuery的。
第一種方法:使用部分功能 - more on this 和closure library
jsfiddle:
var param = 'extra-param';
var partial = function(fn, var_args) {
var args = Array.prototype.slice.call(arguments, 1);
return function() {
// Clone the array (with slice()) and append additional arguments
// to the existing arguments.
var newArgs = args.slice();
newArgs.push.apply(newArgs, arguments);
return fn.apply(this, newArgs);
};
};
$(['joe','james','rick','kirk']).each(partial (function (index,value) {
alert(arguments.length);
alert(arguments[0]);
},param));
第二種方法是
$。每個函數可以接受或者2個參數Index
和Element
(也可稱爲this
) OR 如果你不需要Index
那麼你可以傳遞Array
作爲參數傳遞給$。每次和元件作爲本
警告稱:ARGS僅供內部使用 - 由jQuery的
// 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);
},
它將調用each: function(obj, callback, args)
然後調用callback.apply(obj[ i ], args);
如果你通過數組作爲參數 OTH erwise callback.call(obj[ i ], i, obj[ i ])
;
請注意的申請並調用
示例代碼的區別:http://jsfiddle.net/dekajp/yA89R/1/
var param = 'rick';
$(['joe','james','rick','kirk']).each(function (arg1 , arg2 ,arg3) {
//alert('[this: '+this +'] [arg1: '+ arg1 +'] [arg2:'+arg2+'] [param:'+param+']');
},['hello 1','hello 2','hello 3']);
僅供參考jQuery的每個代碼版本1.9
// args is for internal usage only
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;
},
謝謝! +1爲[jsfiddle.net](http://www.jsfiddle.net) – MarioVW 2011-02-17 20:19:50