首页 > 解决方案 > 如何使用数组中给定的值更改类的 ID

问题描述

我有一个代码,其中有6 classes名称item1item6这些类有 id 有id's 1 to 6..

iwant to change the id of these classes具有在array newids..中给出的值

我试过代码

y[i].id += newids[i-1];

但它给了我错误 Uncaught TypeError: Cannot read property 'id' of undefined..

如何使用数组中给出的 newid 将类 item1 的 id 更改为 item6 ..

我如何实现这一目标?

var newids=[2,1,5,4,6,3];
console.log(newids);

for(i=1;i<=6;i++)
{
var y="item"+i;
x = document.getElementsByClassName(y);
console.log(x);

 y[i].id += newids[i-1];
}
.item1{
	border:2px solid black;
    float:left;
	position:fixed;
	width:5vw;
	height:5vh;
}
.item2{
	border:2px solid black;
	float:left;

	width:5vw;
	height:5vh;
	margin-left:6%;

	}	
.item3{
	border:2px solid black;
	float:left;
	width:5vw;
	height:5vh;
	margin-left:1%;

}		
.item4{
	border:2px solid black;
    float:left;
	width:5vw;
	height:5vh;
	margin-left:1%;

}	
.item5{
	border:2px solid black;
    float:left;
	width:5vw;
	height:5vh;
	margin-left:1%;
}
.item6{
	border:2px solid black;
    float:left;
	width:5vw;
	height:5vh;
	margin-left:1%;
	}

h2{
text-align:center;
margin-top:0%;}	
<div class="item1" id="1">
	<h2>1</h2>
</div>
<div class="item2" id="2">
	<h2>2</h2>
</div>
<div class="item3" id="3">
	<h2>3</h2>
</div>
<div class="item4" id="4">
	<h2>4</h2>
</div>
<div class="item5" id="5">
	<h2>5</h2>
</div>
<div class="item6" id="6">
	<h2>6</h2>
</div>

标签: javascriptjqueryhtml

解决方案


你几乎做对了,你只需要改变两件事:

  1. x = document.getElementsByClassName(y)返回一个HTMLCollection,因此您需要使用索引 0: 获取此集合中的第一个元素
    x = document.getElementsByClassName(y)[0]

  2. 更改y.id += newids[i];为要更改 id 的元素,而不是x.id = newids[i];string 。还要设置(不附加)到您需要使用单个等号(没有)的 id。xy+

请参阅下面的工作示例(检查元素以查看新 ID):

var newids = [2, 1, 5, 4, 6, 3];

for (i = 1; i <= 6; i++) {
  var y = "item" + i;
  x = document.getElementsByClassName(y)[0];

  x.id = newids[i - 1];
}
.item1 {
  border: 2px solid black;
  float: left;
  position: fixed;
  width: 5vw;
  height: 5vh;
}

.item2 {
  border: 2px solid black;
  float: left;
  width: 5vw;
  height: 5vh;
  margin-left: 6%;
}

.item3 {
  border: 2px solid black;
  float: left;
  width: 5vw;
  height: 5vh;
  margin-left: 1%;
}

.item4 {
  border: 2px solid black;
  float: left;
  width: 5vw;
  height: 5vh;
  margin-left: 1%;
}

.item5 {
  border: 2px solid black;
  float: left;
  width: 5vw;
  height: 5vh;
  margin-left: 1%;
}

.item6 {
  border: 2px solid black;
  float: left;
  width: 5vw;
  height: 5vh;
  margin-left: 1%;
}

h2 {
  text-align: center;
  margin-top: 0%;
}
<div class="item1" id="1">
  <h2>1</h2>
</div>
<div class="item2" id="2">
  <h2>2</h2>
</div>
<div class="item3" id="3">
  <h2>3</h2>
</div>
<div class="item4" id="4">
  <h2>4</h2>
</div>
<div class="item5" id="5">
  <h2>5</h2>
</div>
<div class="item6" id="6">
  <h2>6</h2>
</div>


推荐阅读