2012-08-11 29 views
0

我正在爲一個網站編寫一些代碼,該網站使用4個列表項目在頁面上的不同位置顯示/隱藏4個不同的div。jQuery簡化

下面是我在做什麼粗略的例子:

<ul> 
    <li id="first">One</li> 
    <li id="second">Two</li> 
    <li id="third">Three</li> 
    <li id="fourth">Four</li> 
</ul> 

<div id="one">This is the first div</div> 
<div id="two">This is the second div</div> 
<div id="three">This is the third div</div> 
<div id="four">This is the four div</div> 

而且我有一些醜陋的屁股JS代碼怎麼回事,因爲我不記得我的生活/弄清楚如何以簡化它。

$("#first").click(function() { 
    $("#one").fadeIn(); 
    $("#two, #three, #four").fadeOut(); 
}); 
$("#second").click(function() { 
    $("#two").fadeIn(); 
    $("#one, #three, #four").fadeOut(); 
}); 
$("#third").click(function() { 
    $("#three").fadeIn(); 
    $("#two, #one, #four").fadeOut(); 
}); 
$("#fourth").click(function() { 
    $("#four").fadeIn(); 
    $("#two, #three, #one").fadeOut(); 
});​ 

這就是我所需要的,但我知道必須有一個更簡單的方法來做到這一點。這是一個JSFiddle它的工作 - http://jsfiddle.net/claycauley/FBrx5/

如果任何人都可以幫助我理解爲什麼/如何簡化它,這也會很好,因爲我正在努力學習,但卻陷入了困境。

+0

jQuery有一些更簡單的方法,但是(因爲你正在努力學習),一種管理方法就是使用一組元素和一個函數來執行一個函數並隱藏其他函數。 – 2012-08-11 03:09:20

回答

2

嘗試:

$("li").click(function() { 
    $("div:visible").fadeOut(); 
    $("div").eq($(this).index()).fadeIn(); 
});​ 

http://jsfiddle.net/FBrx5/1/

+0

啊,謝謝。這將完美地工作! – 2012-08-11 03:18:44

0

如何像:

<ul id="linky"> 
    <li id="first">One</li> 
    <li id="second">Two</li> 
    <li id="third">Three</li> 
    <li id="fourth">Four</li> 
</ul> 

<div class="first">This is the first div</div> 
<div class="second">This is the second div</div> 
<div class="third">This is the third div</div> 
<div class="fourth">This is the four div</div> 

$("#linky").on("click", "li", function(e) { 
    $("div:visible").fadeOut(); 
    $("." + e.target.id).fadeIn(); 
}); 

http://jsfiddle.net/FBrx5/4/

+0

謝謝你的幫助! – 2012-08-11 03:19:59

1

隨着@Petah的幫助下,我來到了這一點:

$("li").click(function() { 
    if ($("div").eq($(this).index()).is(":visible")) { 
     return false; 
    } 
    else { 
     $("div:visible").fadeOut(); 
     $("div").eq($(this).index()).fadeIn(); 
    } 
     return false; 
});​ 

他的解決方案唯一的問題是它仍然在div上激活,即使它已經可見。它會淡出它,然後回來。通過這個,我可以阻止它發生。