[英]Passing multiple Eval parameters to a JavaScript function from ASPX
[英]Javascript call function as string, with multiple parameters not using eval()
我對javascript很新,但我知道你可以調用一個函數,它由一個字符串表示,這樣:
var function_to_call = window[values['function']];
//Where values['function']='functionName'
到目前為止,我們有:
if(typeof function_to_call == 'function'){
if(values['parameters']!= '')
function_to_call(values['parameters']);
else function_to_call();
};
當然,這不起作用,因為參數在一個字符串中都以“parameter1,parameter2”形式出現,所以你最終得到了
function_to_call("parameter1, parameter2");
而不是
function_to_call(parameter1, parameter2);
有任何想法嗎? 感謝你的時間!
擴展為:
傳遞給函數的參數表示頁面中元素的“id”; 所以調用的函數將嘗試通過執行以下操作來獲取這些元素:
document.getElementById(parameter1);
...some other things...
document.getElementById(parameter2);
我假設參數名稱也代表全局變量。
如果是這樣,你可以將它們分成一個數組,然后將.map()
數組轉換成相關全局變量的新數組。
然后使用.apply()
來調用帶有參數數組的函數。
if (typeof function_to_call == 'function') {
if(values['parameters']!= '') {
var args = values['parameters'].split(",")
.map(function(name) {
return window[name.trim()];
});
function_to_call.apply(window, args);
} else function_to_call();
}
.trim()
和.map()
方法將需要IE8的墊片......但這主要說明了如何做到這一點。 作為替代方案,您可以將正則表達式傳遞給.split()
來處理任何空格。
var args = values['parameters'].split(/\s*,\s*/)...
if(typeof function_to_call == 'function'){
if(values['parameters']!= '')
setTimeout('function_to_call('.values['parameters'].');');
else setTimeout('function_to_call();',0);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.