我正在编写一个脚本,以根据哈希中的字符串更改可见的元素。该脚本将进入博客页面,用户可以在其中按类别过滤博客文章。当用户过滤到某个类别时,该类别将以哈希链接的形式附加到URL。
example.com/#categoryA
到那时,我希望与每个已过滤帖子集相对应的文本框出现在投资组合的旁边。但是,如果用户尚未过滤帖子,或者从过滤帖子转到查看所有帖子,则网址中只有一个哈希,如下所示:
example.com/#
在这种情况下,我希望显示一个默认文本框。
我的脚本(如下所示)执行所有操作,但当URL仅以哈希结尾时,将显示默认文本框。
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以单个哈希结束时显示默认文本框?
我已经设置了一个代码笔(http://codepen.io/ben393/pen/GNVqRX)来演示此操作。
不知道为什么要使用这个frag变量,它永远都不会改变。
您可以执行以下操作
if(window.location.hash.length < 2) {
.....
}
另外,如果没有什么阻止您,则可以使用该onhashchange
事件,而不是通过以下方式连续检查setInterval
$(window).bind('hashchange', hashClassChange);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句