需要在数组中循环,并在javascript中将每个值一次设置为一个类

kqlmhetl  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(357)

我想循环遍历一个数组,并使用javascript将该数组的值设置为“id”。
以下是美国各州的情况

var data =
    [
        'alabama',
        'alaska',
        'arizona',
        'arkansas',
        'california',
        'colorado',
        'connecticut',
        'delaware',
        'florida',
        'georgia',
        'hawaii',
        'idaho',
        'illinois',
        'indiana',
        'iowa',
        'kansas',
        'kentucky',
        'louisiana',
        'maine',
        'maryland',
        'massachusetts',
        'michigan',
        'minnesota',
        'mississippi',
        'missouri',
        'montana',
        'nebraska',
        'nevada',
        'newhampshire',
        'newjersey',
        'newmexico',
        'newyork',
        'northcarolina',
        'northdakota',
        'ohio',
        'oklahoma',
        'oregon',
        'pennsylvania',
        'rhodeisland',
        'southcarolina',
        'southdakota',
        'tennessee',
        'texas',
        'utah',
        'vermont',
        'virginia',
        'washington',
        'west Virginia',
        'wisconsin',
        'wyoming'
    ]

“抓住课堂” let noID = document.getElementsByClassName("card-title"); for循环尝试获取具有类名的每个html元素,并将id设置为数组中的一个状态
例:类名为“card title”的元素#1需要#id为“alabama”的元素#2需要#id为“alaska”

for(let i = 0; i<noID.length; i++){
    for(states of data){
        let stateName = states;
        noID[i].setAttribute("id", stateName);
}

}

o75abkj4

o75abkj41#

你想这么做吗?

var data = [ 'alabama', 'alaska', 'arizona', 'arkansas', 'california', 'colorado', 'connecticut', 'delaware', 'florida', 'georgia', 'hawaii', 'idaho', 'illinois', 'indiana', 'iowa', 'kansas', 'kentucky', 'louisiana', 'maine', 'maryland', 'massachusetts', 'michigan', 'minnesota', 'mississippi', 'missouri', 'montana', 'nebraska', 'nevada', 'newhampshire', 'newjersey', 'newmexico', 'newyork', 'northcarolina', 'northdakota', 'ohio', 'oklahoma', 'oregon', 'pennsylvania', 'rhodeisland', 'southcarolina', 'southdakota', 'tennessee', 'texas', 'utah', 'vermont', 'virginia', 'washington', 'west Virginia', 'wisconsin', 'wyoming' ];

let noID = document.getElementsByClassName("card-title");

for (let i = 0; i < noID.length; i++) {
    noID[i].setAttribute("id", data[i]);
}

相关问题