所以这就是我得到的:
$(document).ready(function () {
if (window.location.href.indexOf("/db1-1") > -1) {
$('.db1sub').closest("db1sub").css("display","block");}
else {
$('.db1sub').closest(".db1sub").css("display","none");}
});
$(document).ready(function () {
if (window.location.href.indexOf("/db1-2") > -1) {
$('.db2sub').closest("db2sub").css("display","block");}
else {
$('.db2sub').closest(".db2sub").css("display","none");}
});
$(document).ready(function () {
if (window.location.href.indexOf("/db1-3") > -1) {
$('.db3sub').closest("db3sub").css("display","block");}
else {
$('.db3sub').closest(".db3sub").css("display","none");}
});
以下是代码适用的部分
<!-- First dashboard selection -->
<li><a class="selected1" href="#">Dashboard 1</a></li>
<div class="db1sub">
<ul>
<li><a href="#">Dashboard a0</a></li>
<li><a href="#">Dashboard a1</a></li>
<li><a href="#">Dashboard a2</a></li>
</ul>
</div>
<!-- Second dashboard selection -->
<li><a class="selected2" href="#">Dashboard 2</a></li>
<div class="db2sub">
<ul>
<li><a href="#">Dashboard b0</a></li>
<li><a href="#">Dashboard b1</a></li>
<li><a href="#">Dashboard b2</a></li>
</ul>
</div>
<!-- Third dashboard selection -->
<li><a class="selected3" href="#">Dashboard 3</a></li>
<div class="db3sub">
<ul>
<li><a href="#">Dashboard c0</a></li>
<li><a href="#">Dashboard c1</a></li>
<li><a href="#">Dashboard c2</a></li>
</ul>
</div>
</ul>
</div>
我想要做的是每当其中一个&lt;单击其中一个列表中的li&gt;,该选项卡将在进入下一页时保持打开状态。现在这个功能非常棒,可以按照我的意愿运行。但是,javascript似乎可以优化,因为db2sub和db3sub的if语句只是在我为db1sub创建if语句后复制和粘贴。有没有办法可以缩小我的javascript代码的大小,这样我就不必继续复制和粘贴所有内容了?
答案 0 :(得分:1)
这样的事情?
$(document).ready(function () {
var obj = {
"db1sub" : "/db1-1",
"db2sub" : "/db1-2",
"db3sub" : "/db1-3"
};
var selectedKey = "";
for ( var key in obj )
{
$('.' + key ).closest( '.' + key ).css("display","none");
if ( window.location.href.indexOf( obj[ key ] ) > -1)
{
selectedKey = key;
}
}
if ( selectedKey.length > 1 )
{
$( '.' + selectedKey ).closest( '.' + selectedKey ).css("display","block");
}
});