簡體   English   中英

根據函數參數動態調用javascript函數

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM