我不認爲你想使用eval
,而是一個匿名函數,因爲當它傳遞給它eval
將評估字符串。
(function($, undefined) {
$.globalEval = function(name, fn, param) {
if (typeof $.fn[name] === "undefined") {
$.fn[name] = function(){
var args = [].concat(
param,
[].slice.call(arguments));
return this[fn].apply(this, args);
};
}
}
})(jQuery);
上述這樣使用:
// Name of function to be called
var strFun = "hide";
// Params that should be passed, can be either array or string
var strParam = "slow";
// Call our plugin
$.globalEval("f", strFun, strParam);
// f() is now available for all elements
// Passing arguments here will add to the current params
// In this case, it will be the callback
$("div").f(function(){ /* Callback that is called when element is hidden */ });
上面是不是真的有用,因爲你可以只直接連接的匿名函數來$.fn.f
,並得到相同的結果,但至少它讓你瞭解它是如何工作的。
見test case on jsFiddle
我很困惑d: – 2011-06-17 06:37:54
@Connor,所以在一開始看它幾次明白他要怎樣做,但我想我想通了;) – mekwall 2011-06-17 06:54:14