我正在編寫一個腳本來根據哈希中的字符串更改哪個元素可見。該腳本將放在博客頁面上,用戶可以按類別過濾博客文章。當用戶過濾到某個類別時,該類別會以哈希鏈接的形式附加到網址中。如果URL哈希不包含任何字符串,請執行函數
example.com/#categoryA
在這一點上,我想對應於每個組篩選的文章的文本框出現在組合並肩作戰。但是,如果用戶沒有過濾的職位,或過濾帖子去查看所有帖子,有URL中的單個哈希是這樣的:
example.com/#
在這種情況下,我需要有一個默認的文本框被顯示。
我的腳本(下圖)除了顯示默認的文本框,只有一個哈希值時纔會顯示。
var frag = window.location.href.split("#");
var hashClassChange = function() {
if (window.location.hash) {
//If the url hash contains commercial, show the commercial box, hide the last active box
if (window.location.hash.indexOf('commercial') == 1) {
$('#box1').addClass("active");
$('#default').removeClass("active");
$('#box2').removeClass("active");
$('#box3').removeClass("active");
$('#box4').removeClass("active");
}
//If the url hash contains hospitality, show the hospitality box, hide the last active box
else if (window.location.hash.indexOf('hospitality') == 1) {
$('#box2').addClass("active");
$('#default').removeClass("active");;
$('#box1').removeClass("active");
$('#box3').removeClass("active");
$('#box4').removeClass("active");
}
//If the url hash contains municipal-institutional, show the municipal/institutional box, hide the last active box
else if (window.location.hash.indexOf('municipal-institutional') == 1) {
$('#box3').addClass("active");
$('#default').removeClass("active");
$('#box1').removeClass("active");
$('#box2').removeClass("active");
$('#box4').removeClass("active");
}
//If the url hash contains residential, show the residential box, hide the last active box
else if (window.location.hash.indexOf('residential') == 1) {
$('#box4').addClass("active");
$('#default').removeClass("active");
$('#box1').removeClass("active");
$('#box2').removeClass("active");
$('#box3').removeClass("active");
}
//If the url hash does not contain any string, show the default box
else if (!frag[1].length) {
$('#default').addClass("active");
$('#box1').removeClass("active");
$('#box2').removeClass("active");
$('#box3').removeClass("active");
$('#box3').removeClass("active");
}
}
};
// repeats function every 500 milliseconds to check if the url hash has been changed
setInterval(hashClassChange, 500);
使默認文本框顯示當URL在一個單一的哈希結束我該如何解決這個腳本?
我有一個codepen設置(http://codepen.io/ben393/pen/GNVqRX)以行動表達這一點。
不是一個使用
onhashchange
事件,而不是連續檢查的答案,但你可以使用'window.location.hash',它將以「#好客」的形式給出散列。然後,你應該創建一個switch語句(或者其他)與完全匹配。像現在這樣使用indexOf可能會導致誤報。 –