Domanda

I have many paragraphs and links, which should show/hide every paragraph independently.

<html>
    
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
            
        </script>
        <script>
            $(document).ready(function() {
                $(".showtext").hide();
                $("#click").click(function() {
                    $(".showtext").next("p").toggle();
                });
            });
        </script>
    </head>
    
    <body> 
        <a href="#" id="click">Click for Show/hide</a>

        <p class="showtext">This text will show/hide</p> <a href="#" class="click">Click for Show/hide</a>

        <p class="showtext">This text will show/hide</p> <a href="#" class="click">Click for Show/hide</a>

        <p class="showtext">This text will show/hide</p> <a href="#" class="click">Click for Show/hide</a>

        <p class="showtext">This text will show/hide</p>...etc dynamicly generated content

    </body>

</html>

EDIT:

Using $(this) does the job as it's pointing to the click event target.

click(function() { 
     $(this).toggle();
  });
È stato utile?

Soluzione 2

here is working fiddle jsfiddle

  <p class="showtext">This text will show/hide</p> 
  <a href="#" class="click">Click for Show/hide</a><br/>
   $(".click").click(function() { 
     $(this).prev("p").toggle();
  });

Altri suggerimenti

Since id must be unique, you need to use class instead:

<a href="#" class="click">Click for Show/hide</a>
<p class="showtext">This text will show/hide</p>

and you can use $(this) to target current clicked anchor:

$('.click').click(function() {
    $(this).next().toggle();    
});

Fiddle Demo

JSFiddle:

http://jsfiddle.net/37ZkH/1/

$(function(){
    $('a').click(function(){
       $(this).next('p').toggle();
    });
});

DON'T use the same id for multiple elements id attribute MUST be unique; use classes and elements nesting/sibling instead.

So switch the id into classes, and use this in the click handler to refer to the clicked element.

Code:

$(document).ready(function () {
    $(".showtext").hide();
    $(".click").click(function () {
        $(this).next(".showtext").toggle();
    });
});

Demo: http://jsfiddle.net/a76qB/

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top