每个元素的jquery切换函数都是独立的

每个元素的jquery切换函数都是独立的,jquery,toggle,Jquery,Toggle,我有许多段落和链接,它们应该独立地显示/隐藏每个段落 <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"> </script> <script> $(document).ready(function() {

我有许多段落和链接,它们应该独立地显示/隐藏每个段落

<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 id="showtext">This text will show/hide</p> <a href="#" id="click">Click for Show/hide</a>

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

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

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

    </body>

</html>

$(文档).ready(函数(){
$(“#showtext”).hide();
$(“#单击”)。单击(函数(){
$(“#showtext”).next(“p”).toggle();
});
});

此文本将显示/隐藏

此文本将显示/隐藏

此文本将显示/隐藏

此文本将显示/隐藏动态生成的内容


因为
id
必须是唯一的,所以您需要改用class:

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

jsiddle:


不要对多个元素使用相同的id id属性必须是唯一的;使用类和元素嵌套/同级

因此,将id切换到类中,并在单击处理程序中使用
this
来引用单击的元素

代码:

演示:

这里是工作小提琴

此文本将显示/隐藏
$(“.click”)。单击(函数(){ $(this.prev(“p”).toggle(); });


id必须是唯一的。改用类。不要对多个元素使用相同的id;使用类和元素嵌套/同级
$('.click').click(function() {
    $(this).next().toggle();    
});
$(function(){
    $('a').click(function(){
       $(this).next('p').toggle();
    });
});
$(document).ready(function () {
    $(".showtext").hide();
    $(".click").click(function () {
        $(this).next(".showtext").toggle();
    });
});
  <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();
  });