我正在爲一個網站編寫一些代碼,該網站使用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/
如果任何人都可以幫助我理解爲什麼/如何簡化它,這也會很好,因爲我正在努力學習,但卻陷入了困境。
jQuery有一些更簡單的方法,但是(因爲你正在努力學習),一種管理方法就是使用一組元素和一個函數來執行一個函數並隱藏其他函數。 – 2012-08-11 03:09:20