Show / hide divs with the same class

I have four images and four divs. When image 1 is clicked, div 1 appears 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()).show();
        });
    });
</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>
+3
source share
3 answers

Edited based on full markup:

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

The above solution is based on the index of the cell in which the links appear .trigger.

Try here

Cm:

+3
source

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

+1
source

.

, , id , , .

.trigger id="trigger-n" (n = 1,2,3,4) .DataList id="DataList-n".

:

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

Source: https://habr.com/ru/post/1784737/


All Articles