[英]How to invoke a Javascript function when another Javascript function is called?
[英]How to invoke javascript function when # is present in URL
當 # 出現在 URL 中時,我試圖調用 JavaScript 函數。 我知道正常行為是導航/滾動到特定標簽。 但是找不到如何調用 JavaScript 函數。
下面的例子很接近但沒有解決我的問題。
var hash = window.location.hash;
if(hash){
// do something
}
您也許能夠利用 hashchange 事件來觸發該函數,假設您不只是想繼續輪詢該位置以查看它是否發生變化。
文檔: https : //developer.mozilla.org/en-US/docs/Web/API/Window/hashchange_event
此代碼片段將偵聽器添加到當前頁面,然后操作散列並觸發函數,顯示新的散列值。 你可以在這里調用任何函數。
window.addEventListener('hashchange', function() { alert(location.hash); }); window.location += "#test";
<script>
if (window.location.href.includes('#')) {
// run your code here
}
</script>
使用 location.hash 函數將解決您的問題
var hash = window.location.hash.replace(/#/g, '');
if(hash){
// found a hash
console.log("heyy I found a hash")'
}
else{
// did not find a hash
console.log("Uh oh")
/*
try using :
window.location = window.location + '#' + "some random variable"
to create a new URL and every time the page loads find the hash and
display the wanted data.
*/
}
PS:這僅在您的 URL 類似於 example.com/#xyz 時才有效,然后它將為您提供 xyz 作為控制台輸出。 這可能聽起來很模糊,但如果你這樣做,你可能會得到一個想法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.