JavaScript increasing variable

2020-04-05 07:56发布

I want to add ID to each element of class .content, and I want each ID to have integer increase by 1. Example:

<div class="content" id="content_1"></div>
<div class="content" id="content_2"></div>

etc. I wrote code which looks like this:

var number = 1;
$(".content").each(function() { 
    $('.content').attr('id', 'content_' + number);
    number++;
});

This code adds content_2 to both of them rather than content_1 and content_2, if I have 3 elements with .content class all of them will have an ID of content_3

Any ideas how I could fix that?

5条回答
孤傲高冷的网名
2楼-- · 2020-04-05 07:57

Use this operator

    var number = 1;
$(".content").each(function() { 
    $('.content').attr('id', 'content_' + number);
    number++;
});

or

var length = $(".content").length;

for(i=1;i<length;i++){

    $('.content')[i].attr('id', 'content_' + i);
}
查看更多
三岁会撩人
3楼-- · 2020-04-05 08:09

You can use the index parameter of the .each function callback instead of your own counter:

$(".content").each(function(i) {
  $(this).prop('id', 'content_' + (i+1));
});
查看更多
孤傲高冷的网名
4楼-- · 2020-04-05 08:12

Try this:

var number = 1;
$(".content").each(function() { 
    this.id = 'content_' + number;
    number++;
});

Note: you could just use vanilla JS to assign the attribute id (no need to use jQuery)

查看更多
神经病院院长
5楼-- · 2020-04-05 08:17

Use this in the each loop :

$(".content").each(function(index) { 
    this.id = 'content_' + index;
});

Otherwise you are selecting all the elements with class .content

JS only approach:

var content = document.querySelectorAll('.content');

[].forEach.call(content, function(item, index) {
  item.id = "content_" + (index+1);
});

ES6/ES2015 syntax:

let content = document.querySelectorAll('.content');

[].forEach.call(content, (item, index) => item.id = `content_${(index+1)}`);
查看更多
别忘想泡老子
6楼-- · 2020-04-05 08:17

Try this

var number = 1;
$(".content").each(function() { 
    this.id = 'content_' + number++;
});

This is iterate single elements one by one rather than taking all elements with .content

查看更多
登录 后发表回答