Convert 'parameter' to jQuery method
Is there a way to convert a parameter to a jQuery method, similar to eval in Javascript?
<script type="text/javascript">
var strFun = "hide";
var strParam = "slow";
var f=eval(strFun)("'" + strParam + "'");
$.globalEval(f);
var oo=$("#test");
oo.f();
</script&g开发者_运维技巧t;
I don't think you want to use eval
, but rather an anonymous function, since eval
will evaluate the string when its passed to it.
(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);
The above is used like this:
// 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 */ });
The above isn't really useful, since you could just attach the anonymous function directly to $.fn.f
and get the same result, but at least it gives you an idea of how it works.
See test case on jsFiddle
精彩评论