我正在尋找執行一個函數,當一個頁面加載了一個特定的散列在URL中。jQuery:當url中存在特定的哈希函數時觸發函數...?
所以,如果我訪問www.mypage.com/hello.html#functionplease
那麼代碼將執行。
任何人都可以指向正確的方向嗎?
任何意見讚賞!
我正在尋找執行一個函數,當一個頁面加載了一個特定的散列在URL中。jQuery:當url中存在特定的哈希函數時觸發函數...?
所以,如果我訪問www.mypage.com/hello.html#functionplease
那麼代碼將執行。
任何人都可以指向正確的方向嗎?
任何意見讚賞!
var h = location.hash.substr(1);
if (h == 'functionplease')
functionplease();
substr(1)刪除散列中的#。
許多功能?沒問題!
switch(location.hash.substr(1)) {
case 'buy': buy(); break;
case 'sell': sell(); break;
case 'other': other(); break;
}
下面應該工作:
<script type="text/javascript">
//check if hash tag exists in the URL
if(window.location.hash)
{
//set the value as a variable, and remove the #
var hash_value = window.location.hash.replace('#', '');
//check value of hash
if (hash_value == 'functionplease'){
// execute code
}
}
</script>
希望這有助於!
var pathname = window.location.pathname;
if(pathname.indexOf("#") != -1){
//call your function
}
嘗試:
<script type="text/javascript">
window.onload = function() {
setInterval(pollHash, 100);
}
var lasthash = '';
function pollHash() {
if (window.location.hash == lasthash) { return; }
lasthash = window.location.hash;
console.log('hash is changed! Current hash is: ' + lasthash);
switch (lasthash) {
case '???' :
/* do something */
break;
default:
/* do nothing */
break;
}
}
</script>
,看一下:http://ajaxpatterns.org/Unique_URLs#Unique_URL_Sum_Demo
而不是輪詢使用onhashchange事件https://developer.mozilla.org/en/docs/Web/API/WindowEventHandlers/onhashchange – rtack
完美,謝謝! – Cordial