jQuery Simplify

天大地大妈咪最大 提交于 2019-12-12 02:25:58

问题


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.


回答1:


Try:

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

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




回答2:


With the help of @Petah I came up with this:

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

The only problem with his solution was that it still activated on a div even if it was already visible. It would fade it out, then back in. With this I can stop that from happening.




回答3:


How about something like:

<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/



来源:https://stackoverflow.com/questions/11911551/jquery-simplify

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!