【发布时间】:2012-06-14 09:18:07
【问题描述】:
我终于拼凑了一些适用于我的问题here 的代码。但是,它看起来很长,因为我已经为刷新具有特定哈希的页面以及通过单击选项卡访问同一页面时创建了单独的函数。
$(document).ready(function () {
$(function () {
var loc = window.location.href; // For when Hazel is refreshed
if (/Hazel/.test(loc)) {
$("#tab1,#tab2,#tab3,#tab4").removeClass("r p c").addClass("h");
$("#tab2").removeClass("tail");
$("#tab3, #tab4").addClass("tail");
}
});
$(function () {
var loc = window.location.href; // For when Red is refreshed
if (/Red/.test(loc)) {
$("#tab1,#tab2,#tab3,#tab4").removeClass("h p c").addClass("r");
$("#tab3, #tab2").removeClass("tail");
$("#tab4").addClass("tail");
}
});
$(function () {
var loc = window.location.href; // For when Pink is refreshed
if (/Pink/.test(loc)) {
$("#tab1,#tab2,#tab3,#tab4").removeClass("h r c").addClass("p");
$("#tab3, #tab4").removeClass("tail");
$("#tab2").addClass("tail");
}
});
});
$(function () {
var loc = window.location.href; // For when Cyan is refreshed
if (/Cyan/.test(loc)) {
$("#tab1,#tab2,#tab3,#tab4").removeClass("h r p").addClass("c");
$("#tab4").removeClass("tail");
$("#tab3, #tab2").addClass("tail");
}
});
$("#tab1").click(function () {
$(window).bind("hashchange", function () {
var loc = window.location.href; // For when Hazel tab is clicked
if (/Hazel/.test(loc)) {
$("#tab1,#tab2,#tab3,#tab4").removeClass("r p c").addClass("h");
$("#tab2").removeClass("tail");
$("#tab3, #tab4").addClass("tail");
}
});
});
$("#tab2").click(function () {
$(window).bind("hashchange", function () {
var loc = window.location.href; // For when Red tab is clicked
if (/Red/.test(loc)) {
$("#tab1,#tab2,#tab3,#tab4").removeClass("h p c").addClass("r");
$("#tab3, #tab2").removeClass("tail");
$("#tab4").addClass("tail");
}
});
});
$("#tab3").click(function () {
$(window).bind("hashchange", function () {
var loc = window.location.href; // For when Pink tab is clicked
if (/Pink/.test(loc)) {
$("#tab1,#tab2,#tab3,#tab4").removeClass("h r c").addClass("p");
$("#tab3, #tab4").removeClass("tail");
$("#tab2").addClass("tail");
}
});
});
$("#tab4").click(function () {
$(window).bind("hashchange", function () {
var loc = window.location.href; // For when Cyan tab is clicked
if (/Cyan/.test(loc)) {
$("#tab1,#tab2,#tab3,#tab4").removeClass("h r p").addClass("c");
$("#tab4").removeClass("tail");
$("#tab3, #tab2").addClass("tail");
}
});
});
});
可以简化吗?我已经尝试过,但到目前为止,代码只是中断了。
【问题讨论】:
-
是的。你试过什么,请给我们看看那个代码?
-
为什么将前三个 addOnDOMready-statements 包装在另一个 $(document).ready 中?
-
这属于codereview.stackexchange.com而不是SO。
-
有没有可能四种颜色都没有刷新?还是在 URL 中总是有四个正则表达式之一?我正在考虑 if-elseif-elseif-else。
-
@Bergi:我会看看我是否可以复制它们,因为我已经将我的保存文件恢复为上面的代码,因为它到目前为止对我有用;但根据 Christoph 的建议,我想我不得不向 Code Review 提出这个问题。
标签: javascript jquery tabs simplify simplification