JavaScript increasing variable

前端 未结 5 1225
南方客
南方客 2021-01-18 11:37

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

相关标签:
5条回答
  • 2021-01-18 11:47

    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)}`);
    
    0 讨论(0)
  • 2021-01-18 11:48

    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);
    }
    
    0 讨论(0)
  • 2021-01-18 11:59

    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

    0 讨论(0)
  • 2021-01-18 12:08

    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));
    });
    
    0 讨论(0)
  • 2021-01-18 12: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)

    0 讨论(0)
提交回复
热议问题