[英]call value inside a JS variable as a JS function name
您好,我有一個執行動作的函數,但函數名稱在變量內...
下面的代碼將獲取URL的哈希部分示例:#JHON並刪除#並將其存儲在URLHASH變量中。
var urlhash = document.location.hash;
urlhash = urlhash.replace(/^.*#/, '');
總是在變量內的值中有一個函數名,而我想將該變量內的值作為函數名調用
window.onload=function() {
Value inside URLHASH variable should run as a name of a variable. example: jhon();
};
可能嗎 ? 我嘗試了一些代碼,但它將變量名稱作為函數而不是變量內部的值調用..幫助我..
您可以像訪問數組索引一樣訪問對象的屬性,例如,可以通過以下方式運行getElementById
:
document["getElementById"]("#myid");
這樣,如果您事先知道函數將成為哪個對象的成員,則可以通過這種方式訪問它。 全局范圍內的函數是window對象的方法。 但是,如果散列可能包含#document.write()
類的表達式,則必須進行一些解析。 它可以像這樣工作
window.onload=function() {
var urlhash = document.location.hash, current_element = window;
urlhash = urlhash.replace(/^.*#/, '');
elements = urlhash.split(".");
for(var i=0; i<elements.length; i++){
current_element = current_element[elements[i]];
}
//execute the actual function
current_element();
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.