2011-06-17 42 views
0

有沒有辦法將參數轉換爲jQuery方法,類似於JavaScript中的eval?將'參數'轉換爲jQuery方法

<script type="text/javascript"> 
var strFun = "hide"; 
var strParam = "slow"; 

var f=eval(strFun)("'" + strParam + "'"); 
$.globalEval(f); 
var oo=$("#test"); 
oo.f(); 
</script> 
+0

我很困惑d: – 2011-06-17 06:37:54

+0

@Connor,所以在一開始看它幾次明白他要怎樣做,但我想我想通了;) – mekwall 2011-06-17 06:54:14

回答

3

我不認爲你想使用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