我正在尝试根据哈希字符串中的函数名称来调用函数。我有以下代码:
$(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
调用时,一切都会按预期进行。但是,当警报
被注释时,它不起作用。
有什么想法吗?
最佳答案
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)
关于JavaScript:在 hashchange 上按名称调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13978756/