2012-12-20 53 views
0

我試圖調用給定函數名稱的哈希字符串中的函數。我有以下代碼:JavaScript:通過hashchange上的名稱調用函數

$(window).on('hashchange', function() { 
    //alert(location.hash.substring(1, location.hash.length)); 
    window[location.hash.substring(1, location.hash.length)]; 
}); 

function test() { 
    alert('123!'); 
} 

有趣的是,當我取消了alert電話,一切正常。然而,當alert被評論時,它不起作用。

任何想法?

+4

在哪裏被縮短你調用一個函數? –

+0

聽起來像你試圖做的將打開[重大XSS洞](https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)) – Bergi

+0

@Bergi:我只用這個移動網絡應用內的頁面導航。被調用的函數用於通過API調用呈現頁面,這需要進行身份驗證,所以我不認爲這確實會帶來安全風險(但如果我錯了,請糾正我)。謝謝! –

回答

4
window[location.hash.substring(1, location.hash.length)]; 

不調用函數。

如果你想叫他的名字是location.hash.substring(1, location.hash.length)的功能,你可以這樣做

window[location.hash.substring(1, location.hash.length)](); 

旁註:

location.hash.substring(1, location.hash.length) 

可以

location.hash.slice(1) 
+1

+1''location.hash.slice(1)' –

+0

是的,忘記了括號。謝謝! –