javascript - 如何使用数组中给定的值更改类的 ID
问题描述
我有一个代码,其中有6 classes
名称item1
,item6
这些类有 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>
解决方案
你几乎做对了,你只需要改变两件事:
x = document.getElementsByClassName(y)
返回一个HTMLCollection,因此您需要使用索引 0: 获取此集合中的第一个元素x = document.getElementsByClassName(y)[0]
。- 更改
y.id += newids[i];
为要更改 id 的元素,而不是x.id = newids[i];
string 。还要设置(不附加)到您需要使用单个等号(没有)的 id。x
y
+
请参阅下面的工作示例(检查元素以查看新 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>
推荐阅读
- python - 通过 Python 脚本/代码获取特定的 dict 值
- c++ - 如何弃用 C++ 标头?
- mysql - 将两个相等的条件放入一个 WHERE 子句 - SQL
- tree - 在 openlayers 中使用组进行图层控制
- mysql - 错误 1064,“您的 SQL 语法有错误” Python Django
- python - Python中Matlab的spmak等价物
- android - Apple Silicon Android Studio 模拟器:错误:找不到模拟器可执行文件
- android - Android Room 插入不写入数据库
- testing - 如何使用 testcafe 在 slack 报告中打印测试环境
- jenkins - Jenkins 为什么要在 tokenize(', ').join('\n') 之后留下 [ ]?