【问题标题】:Jquery: Dynamic adding <id> depending on <div>Jquery:根据 <div> 动态添加 <id>
【发布时间】:2011-05-24 03:03:09
【问题描述】:

让我们根据 DIV 的数量在 DIV 标签上动态添加 ID

<div class="panel" id="">
  ...
  ...
</div>
<div class="panel" id="">
  ...
  ...
</div>
<div class="panel" id="">
  ...
  ...
</div>

我们想要达到的结果是使用jquery

<div class="panel" id="1">
  ...
  ...
</div>
<div class="panel" id="2">
  ...
  ...
</div>
<div class="panel" id="3">
  ...
  ...
</div>

我试图做这样的代码,但它不起作用

$panel.each(function(i) {
  $(this).attr('id', ($(i+1)));

【问题讨论】:

    标签: jquery html


    【解决方案1】:
    $('.panel').each(function(i) {
      $(this).attr('id', i+1);
    });
    

    http://jsfiddle.net/rjptR/

    【讨论】:

      【解决方案2】:

      问题出在最后一行:

        $(this).attr('id', ($(i+1)));
      

      你为什么用($())包裹i+1

      应该只是

        $(this).attr('id', i+1); 
      

      【讨论】:

      • 谢谢安德烈!我还不知道基本的编码。我知道该使用什么,只是我不知道如何使用它们。但我知道下次我会记住他们的。再次感谢安德烈!
      【解决方案3】:
      i=0;
      $('.panel').each(function() {
          i++;
          $(this).attr('id', i);
      });
      

      【讨论】:

        【解决方案4】:
         $(document).ready(
                function () {
                    var counter = 1;
                    $(".panel").each(
                        function () {
                            $(this).attr("id", counter);
                            counter++;
                        }
                    );
                }
        );
        

        【讨论】:

          猜你喜欢
          • 2011-08-28
          • 2023-03-12
          • 2013-01-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-08-10
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多