0

ハッシュ文字列で関数名を指定して関数を呼び出そうとしています。次のコードがあります。

$(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

1 に答える 1

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)
于 2012-12-20T19:04:40.027 に答える