如何使用jquery显示for循环中每个链接的标记?

时间:2013-07-02 06:27:22

标签: jquery-ui

我在for循环中有一个id为'b1'的div。这个div是可点击的,当我点击这个链接时,我想显示与该div相关的标签,以显示在特定的div b1下方。但是根据我的代码,它只显示第一个div的标签.Below是我的代码

<head>

<script type="text/javascript">
<script src="http://code.jquery.com/jquery-1.10.1.js"></script>

    $(document).ready(function(){
    $("#b1").click(function(){
      $('#newdiv').slideToggle();  
        $id= $(this).attr('data-target');
        $src =  $('#newdiv'); 
        $idTrg = $('#'+$id);
        $src.html($idTrg.html());

    });
});
        </script>

       <style>
#newdiv{
    width:100px;
    height:100px;
    background-color:orange;
}
/*#newdiv:hover{
    text-decoration:underline;
}*/
</style> 
    </head>
<body>
   <?php for($i=1;$i<9; $i++): ?>
           <div id="whole">
<div id="b1" data-target="<?php  echo $i; ?>">Content<?php  echo $i; ?></div>
<div id="newdiv"  style="display:none" ></div>
</div>
<?php endfor; ?>

   <?php for($j=1;$j<9; $j++): ?>
<div id="<?php echo $j ;?>" style="display:none">
    Main contents<?php echo $j; ?>
    <div id="another">Inside Another one<?php echo $j; ?></div>
</div>
    <?php endfor; ?>
</body>

如何在点击链接时让每个div内容显示在它下面?有人可以帮我解决这个问题

1 个答案:

答案 0 :(得分:1)

首先,您需要验证生成的HTML(http://validator.w3.org/)。您不能在另一个元素中包含script元素。

ID必须在HTML文档中是唯一的,并且jQuery内置了“修复”,因此选择ID总是只返回一个元素。通过在循环中使用div,它会在生成的HTML代码中多次输出(查看浏览器中生成的源代码)。

您必须将ID替换为类。

此外$('#newdiv')(如果使用类,则为$('.newdiv'))将选择具有该ID /类的任何/所有元素,而不是具有被点击元素旁边的元素。您可以使用.next()来查找它。

最后一些通用的代码风格建议:

  • 使用更好的ID /类名称。 b1并不意味着什么。你交换了“源”和“目标”的含义。
  • 使用var声明所有变量,否则它们将成为全局变量。
  • 请勿使用$为所有变量添加前缀。有些人对保存jQuery对象的变量使用$前缀,这是好的(但不推荐),但对其他变量肯定没有意义。
  • 更干净地缩进代码,以便更好地阅读。

<head>
  <script src="http://code.jquery.com/jquery-1.10.1.js"></script>
  <script type="text/javascript">
    $(document).ready(function(){
      $(".b1").click(function(){
        var $target = $(this).next();
        $target.slideToggle();  
        var id = $(this).attr('data-target');
        $src = $('#'+id);
        $target.html($src.html());
      });
    });
  </script>

  <style>
    .newdiv{
      width:100px;
      height:100px;
      background-color:orange;
    }
  </style> 
</head>
<body>
  <?php for($i=1;$i<9; $i++): ?>
    <div class="whole">
      <div class="b1" data-target="<?php  echo $i; ?>">Content<?php  echo $i; ?></div>
      <div class="newdiv"  style="display:none" ></div>
    </div>
  <?php endfor; ?>

  <?php for($j=1;$j<9; $j++): ?>
    <div id="<?php echo $j ;?>" style="display:none">
      Main contents<?php echo $j; ?>
      <div class="another">Inside Another one<?php echo $j; ?></div>
    </div>
  <?php endfor; ?>
</body>