gpt4 book ai didi

javascript - 根据函数参数动态调用javascript函数

转载 作者:行者123 更新时间:2023-11-30 16:52:26 25 4
gpt4 key购买 nike

我有一个 jQuery 函数,它根据我应该调用另一个 jQuery 函数的参数接受很少的参数。

例子:

arg0 = "Launch"
arg1 = "menu"

例子:

(function($)
{
preRender: function(arg0,arg1)
{
var nextFuncName = arg0+arg1; //launchmenu
nextFuncName() // hope to call the function name framed from the number of arguments
}
})(jQuery);

(function($)
{
launchmenu: function()
{
console.log("Launchmenu called");
}
})(jQuery);

我引用了以下链接 calling a jQuery function named in a variable但我不想使用 eval() 或窗口对象。

是否可以使用$.proxy 或任何其他方法来实现此功能,是否可以使用underscore.js 来实现此功能?

我们将不胜感激。

最佳答案

尝试使用 jQuery 对象

…or much better an own, local object, instead of polluting the global jQuery namespace.


Merge them so that you use localObject for launchmenu but $ for preRender


(function($) {

var localObject = {};

function launchmenu() {
console.log("Launchmenu called")
}

function preRender(arg0, arg1) {
var nextFuncName = arg0 + arg1;
if (nextFuncName in localObject) {
localObject[nextFuncName]()
} else {
console.log(typeof nextFuncName)
}
}


localObject.launchmenu = launchmenu;
$.preRender = preRender;

}(jQuery));

$(function() {
$.preRender("launch", "menu");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>

关于javascript - 根据函数参数动态调用javascript函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30316418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com