开发者

Jquery: Dynamic adding <id> depending on <div>

Let's dynamically add IDs on our DIV tag, depending on the number of DIVs

<div class="panel" id="">
  ...
  ...
</div>
<div class="panel" id=""&开发者_高级运维gt;
  ...
  ...
</div>
<div class="panel" id="">
  ...
  ...
</div>

the result that we would like to achieve is using jquery

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

i tried to do a code like this but it is not working

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


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

http://jsfiddle.net/rjptR/


The problem is with the last line:

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

Why do you wrap i+1 with ($())?

It should be just

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


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


 $(document).ready(
        function () {
            var counter = 1;
            $(".panel").each(
                function () {
                    $(this).attr("id", counter);
                    counter++;
                }
            );
        }
);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜