开发者

jQuery nav arrays, looking for an elegant solution

I've been trying to think of the most elegant way to achieve the following...

I've got the following nav structure:

    <div class="menu-wrap">
    <ul id="smenu">
      <li><a class="selected" href="#">1</a></li>
      <li><a class="" href="#">2</a></li>
      <li><a class="" href="#">3</a></li>
      <li><a class="" href="#">4</a></li>
      <li><a class="" href="#">5</a></li>
      <li><a class="" href="#">6</a></li>
      <li><a class="" href="#">7</a></li>
    </ul>
  </div>

And this div elsewhere on the page:

    <div class="desc-wrap">
    <p>blah blah blah</p>
    <p>blah blah blah</p>
    <p>blah blah blah</p>
    <p>blah blah blah</p>
    <p>blah blah blah</p>
    <p>blah blah blah</p>
    <p>blah blah blah</p>
</div>

the p's are all hidden by default; if I click the first li, I want the first p to show up, etc. Simple right? I've got it working several different ways, but I keep thinking I should be able to do it in far fewer lines.

Here's my super lame one, with class names added:

        $("#smenu li").click(function() {
    $(".desc-wrap p").hide();       
});
$("li.desc-one").click(function() {
    $("p.desc-one").show();
});
$("li.desc-two").click(function() {
    $("p.desc-two"开发者_JS百科).show();
});
$("li.desc-three").click(function() {
    $("p.desc-three").show();
});
$("li.desc-four").click(function() {
    $("p.desc-four").show();
});
$("li.desc-five").click(function() {
    $("p.desc-five").show();
});
$("li.desc-six").click(function() {
    $("p.desc-six").show();
});
$("li.desc-seven").click(function() {
    $("p.desc-seven").show();
});

And here's the start of my array attempt, but you can see where that's going:

        var mappedPs = $(".desc-wrap p").map(function (index) {
    if (index == 0) {
        $(this).show();
    }
    else {
        $(this).hide();
    }
});
var mappedList = $("#smenu li").map(function (index) {
    if (index == 0) {
        $("#smenu li").click(function() {
            $(mappedPs[0]).show();
        });
    }
    else {
        $(mappedPs[1,2,3,4,5,6]).hide();
    }
});

Am I missing something obvious? I feel like this should be far simpler than it's turning out...


Why not just use .index()?

$('#smenu li').click(function(){
    $('.desc-wrap p').hide().eq($(this).index()).show();
});


$('#smenu li').each(function(index) {
  $(this).click(function() {
    $('.desc-wrap p:eq('+index+')').show();
  });
});

OR (this will hide any visible paragraph tags)

$('#smenu li').each(function(index) {
  $(this).click(function() {
    $('.desc-wrap p').hide().filter(':eq('+index+')').show();
  });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜