开发者

Show/hide divs with same class

I have four images and four divs. When image 1 is clicked, div 1 should appear and all others should be hidden, etc. Each div has the same class name.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<title>Untitled 1</title>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script type="text/javascript">
    $(window).load(function(){
        $(".DataList").hide();
        $(".DataList:first").show();    
        $(".trigger").click(function() {
            $(".DataList").hide();
            $(".DataList").eq($(this).index()).sho开发者_JS百科w();
        });
    });
</script>
</head>

<body>

<div id="LinkBar">
    <table border="0">
        <tr>
            <td>
               <a class="trigger" href="#"><img src="Package1.gif" /></a> </td>
            <td>
               <a class="trigger" href="#"><img src="Package2.gif" /></a> </td>
        </tr>
    </table>
</div>

<div class="DataList">
    <div class="Description">
        <ul class="Package">
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
        </ul>
        <div class="Hidden">
            1 </div>
    </div>
</div>

<div class="DataList">
    <div class="Description">
        <ul class="Package">
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
        </ul>
        <div class="Hidden">
            2 </div>
    </div>
</div>

</body>

</html>


Edited, based on your full markup:

$(".DataList").hide();
$(".DataList:first").show();
$(".trigger").click(function() {
    $(".DataList").hide();
    $(".DataList").eq($(this).closest("td").index()).show();
});

The above solution relies on the cell index in which the .trigger links appear.

Try it here

See:

  • http://api.jquery.com/closest/
  • http://api.jquery.com/eq/
  • http://api.jquery.com/eq-selector/
  • http://api.jquery.com/index/


Give different ids to div and use $("document.getElementById('specificDivId')").hide();


You need a way to identify corresponding links and targets.

If they are ordered, then you could use the relative position, though usually it would be best to add id fields to both, so that they can be matched if they get out of order.

Try naming all .trigger fields with id="trigger-n" (n=1,2,3,4), and .DataList fields with id="DataList-n".

Then you can match one with the other like so:

$('.trigger').click(function() {
  var cTriggerID = $(this).attr('id').replace(/^.*-(\d+)$/, '$1');
  var cDataList = $('#DataList-' + cTriggerID);
  cDataList.slideToggle();
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜