我正在使用localscroll jquery插件,当有人在url的末尾输入带有#标签的url时我想要一个安全的选项,所以我写了这些代码行:
if (window.location.hash == "#home") {
$('#menu-main a').removeClass('sel');
$("#a1").addClass("sel");
$('#about,#collections,#contact,#brides,#gallery').animate({ opacity: 0 }, 0);
} else if (window.location.hash == "#about") {
$('#menu-main a').removeClass('sel');
$("#a2").addClass("sel");
$('#home,#collections,#contact,#brides,#gallery').animate({ opacity: 0 }, 0);
} else if (window.location.hash == "#collections") {
$('#menu-main a').removeClass('sel');
$("#a3").addClass("sel");
$('#about, #home, #contact, #brides, #gallery').animate({ opacity: 0 }, 0);
} else if (window.location.hash == "#brides") {
$('#menu-main a').removeClass('sel');
$("#a4").addClass("sel");
$('#about, #collections, #contact, #home, #gallery').animate({ opacity: 0 }, 0);
} else if (window.location.hash == "#gallery") {
$('#menu-main a').removeClass('sel');
$("#a5").addClass("sel");
$('#about, #collections, #home, #contact, #brides').animate({ opacity: 0 }, 0);
} else if (window.location.hash == "#contact") {
$('#menu-main a').removeClass('sel');
$("#a6").addClass("sel");
$('#about, #collections, #home, #brides, #gallery').animate({ opacity: 0 }, 0);
} else if (window.location.hash == "") {
$('#menu-main a').removeClass('sel');
$("#a1").addClass("sel");
$('#about,#collections,#contact,#brides,#gallery').animate({ opacity: 0 }, 0);
}
但是,肯定必须有更好的解决方案,一些foreach函数可能,因为我不是真正的jquery大师,我想问你的建议......
谢谢,Mart
答案 0 :(得分:1)
如果有人对我的解决方案感兴趣,我解决了它:
var hash = window.location.hash;
var cats = {};
cats['#home'] = 'a1';
cats['#about'] = 'a2';
cats['#collections'] = 'a3';
cats['#brides'] = 'a4';
cats['#gallery'] = 'a5';
cats['#contact'] = 'a6';
cats[''] = 'a1';
$("#menu-main a").removeClass('sel');
$("#" + cats[hash]).addClass("sel");
if (!hash){
$('#about,#collections,#contact,#brides,#gallery').animate({ opacity: 0 }, 0);
} else {
$.each(cats, function(key, value) {
if (key != hash){
$(key).animate({ opacity: 0 }, 0);
}
});
}
答案 1 :(得分:0)
function makeSelect(){
var hash = window.location.hash;
$("#menu-main a").removeClass('sel');
$("#"+hash).addClass("sel");
$('#about,#collections,#contact,#brides,#gallery').animate({ opacity: 0 }, 0);
}
你可以使用这样的东西,如果你可以将对象名称更改为哈希值,或者为它们制作哈希图