0

I want three < li > appended in the aside area of the body of the HTML document

  • Hey1
  • Hey2
  • Hey3
  • and to each of them attached a click toggle function so that it can show and hide an appropriate div in the body of the HTML.

       </aside>
      <div id="id1" > I am the  one </div>
      <div id="id2" > I am the  second</div>
      <div id="id3" > I am the  third</div>
      </body>
    

    For example the < li > Hey1 attached click function will ONLY toggle the div with the id="id1" and so on

    the code I have written is

       $(document).ready(function() {   $("div").hide();    
       jQuery.each([1,2,3], function(n,value){ n++; 
    
        $('aside').append("<li> hey"+value+" </li>").click(function(){$('#id'+value).toggle()});
        });
        })
    

    Now the code creates the < li > 's all right and it attaches to them the click function. The problem is that whichever of the < li > I click all three of the < div > s toggle
    when what i specifically want is that when , say the < li > Hey1 is clicked THEN ONLY the area with the < div id="id1" > I am the one < /div> will be shown and hidden.

    I am thankful to any help

    2 Answers 2

    1

    You're not attaching the click handler to the li's, but to the aside, do :

    $(document).ready(function() {   
        $("div").hide();    
        $.each([1,2,3], function(n,value){
          $('<li />', {text: 'hey'+value}).appendTo('aside').on('click', function() {
              $('#id'+value).toggle();
          });
        });
    });
    
    Sign up to request clarification or add additional context in comments.

    Comments

    0

    that's because you attach click event to the aside, not li

    $(document).ready(function() {   $("div").hide();    
        $.each([1,2,3], function(n,value){
            n++; 
            $li = $("<li> hey"+value+" </li>").click(function(){
                $('#id'+value).toggle();
            });
            $('aside').append($li);
        });
    })
    

    Comments

    Your Answer

    By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.