Search code examples
javascriptjqueryhtmlhyperlinkhref

trouble with simple jQuery script


I'm new to jQuery and I want to create my own web page. So my problem is if my menu is using href to link each item to its specified content, like this..

<li><a href="#doc1">Doc1</a></li>
<li><a href="#doc2">Doc2</a></li>
<li><a href="#doc3">Doc3</a></li>

<script>
$(document).ready(function(() {
     $(a).click(function() {
         $(b).show();
    });
});
</script>

What should I put in 'a' and 'b'? I've tried Googling this, but all the examples didn't show the complete script. I used to do it like this:

<li id="doc1menu">Doc1</li>
<script>
$(document).ready(function() {
    $("#doc1menu").click(function() {
        $("#doc1content").show();
    });
});
</script>

But now I want a single function that could be used for all items on my menu, instead of doing one function for each item.


Solution

  • HTML

    <li><a data-content="doc1" href="#doc1">Doc1</a></li>
    <li><a data-content="doc2" href="#doc2">Doc2</a></li>
    <li><a data-content="doc3" href="#doc3">Doc3</a></li>
    
    <div id="doc1" class="content">
      doc1
    </div>
    <div id="doc2" class="content">
      doc2
    </div>
    <div id="doc3" class="content">
      doc3
    </div>
    

    Script

    $(function() {
    
        //hide all content
        $(".content").hide();
    
      //meun function
      $("a").click(function() {
        var attr = $(this).attr("data-content");
        $(".content").hide();
        $("#" + attr).show();
      });
    
    });
    

    https://jsfiddle.net/ynpsq1wp/1/