本文介绍了JavaScript增加变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想为类在每个循环中使用 this :
$(。content)。each(function(index){
this.id ='content_'+ index;
});
否则,您将选择具有类 .content $ c的所有元素
JS的唯一方法:
$ b $
var content = document .querySelectorAll( '内容');
[] .forEach.call(content,function(item,index){
item.id =content_+(index + 1);
});
ES6 / ES2015语法:
let content = document.querySelectorAll('。content');
[] .forEach.call(content,(item,index)=> item.id =`content _ $ {(index + 1)}`);
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?
解决方案
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)}`);
这篇关于JavaScript增加变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!