[英]Dynamically call javascript function based on function arguments
我有一個 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);
我引用了以下鏈接, 調用以變量命名的 jQuery 函數,但我不想使用eval()
或 window 對象。
是否可以使用$.proxy
或任何其他方法來實現此功能,是否可以使用 underscore.js 來實現?
任何幫助將不勝感激。
嘗試使用jQuery
對象
...或者更好的自己的本地對象,而不是污染全局 jQuery 命名空間。
合並它們,以便您使用
localObject
作為launchmenu
但使用$
作為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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.