jQuery简化 [英] jQuery Simplify
问题描述
我正在为一个网站编写一些代码,该网站使用4个列表项在页面上的不同位置显示/隐藏4个不同的div.
这是我在做什么的一个粗略例子:
<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/ >
如果有人可以帮助我理解为什么/如何简化它,那也很好,因为我试图学习但变得很沮丧.
尝试:
$("li").click(function() {
$("div:visible").fadeOut();
$("div").eq($(this).index()).fadeIn();
});
I am writing some code for a website that uses 4 list items to show/hide 4 different divs at a different place on the page.
Here is a rough example of what I am doing:
<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>
And I've got some ugly arse JS code going on, and for the life of me I can't remember/figure out how to simplify it at all.
$("#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();
});
This does what I need it to, but I know there has to be a simpler way of doing it. Here is a JSFiddle of it working - http://jsfiddle.net/claycauley/FBrx5/
If any one can help me understand why/how to simplify it that would be great also, because I am trying to learn but getting stumped.
Try:
$("li").click(function() {
$("div:visible").fadeOut();
$("div").eq($(this).index()).fadeIn();
});
这篇关于jQuery简化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!