2011-06-17 41 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