首页 > 解决方案 > 从数组中设置元素的 ID

问题描述

抱歉,如果这已经得到解答,但我真的找不到解决方案。我对用 js 进行开发还很陌生,而且我有点卡在一些代码上。

基本上,我试图在每次加载窗口时更改 div 的 id。

我设法在每次加载时从数组中随机获取一个值,但我没有设法将它作为 id 分配给我的元素(使用 set 属性)。

这是代码:

// on load change type
window.onload = changeType;

// array of styles
let styles = ['style1', 'style2', 'style3', 'style4'];

// shuffle array 
function shuffle(styles) {
    var ctr = styles.length,
        temp, index;

    // while there are elements in array
    while (ctr > 0) {

        // pick random index
        index = Math.floor(Math.random() * ctr);

        // decrease ctr by one
        ctr--;

        // swap last element and ctr
        temp = styles[ctr];
        styles[ctr] = styles[index];
        styles[index] = temp;
    }
    // return array
    return styles;
}


// To avoid having them same value twice
// shuffle array
let shuffleStyle = shuffle(styles);

// pick random value
let randomStyle = styles[Math.floor(Math.random() * styles.length)];

// test
console.log(randomStyle);

// value to string
let randomFinal = randomStyle.toString();

//test
console.log(randomFinal);


// replace id by random array value
function changeType() {
    document.getElementById("style").setAttribute("id", randomFinal);
}

标签: javascriptarraysgetelementbyidsetattribute

解决方案


我设法弄清楚了,我定位了我的元素,然后使用我的数组中的值添加了一个类!

这是代码(抱歉评论是法语)

// au chargement je lance fonction changeType
window.onload = changeType;

// je fais un array de styles
let styles = ['style1', 'style2', 'style3', 'style4'];

// je mélange mon array
function shuffle(styles) {
    var ctr = styles.length,
        temp, index;

    // tant qu'il y a des éléments dans l'array
    while (ctr > 0) {
        // je choisis un index random
        index = Math.floor(Math.random() * ctr);
        // j'enlève 1 à ctr
        ctr--;
        // j'échange le dernier élément avec le ctr
        temp = styles[ctr];
        styles[ctr] = styles[index];
        styles[index] = temp;
    }
    // je retourne l'array
    return styles;
}


// POUR ÉVITER DEUX FOIS LA MÊME VALEUR
// je shuffle mon array
let shuffleStyle = shuffle(styles);

// je choisis une valeur au hasard
let randomStyle = styles[Math.floor(Math.random() * styles.length)];

// je teste
console.log(randomStyle);

// valeur en string
let randomFinal = randomStyle.toString();

console.log(randomFinal);


// fonction pour remplacer l'id par valeur de mon array
function changeType() {
    let element = document.getElementById("style");
    element.classList.add(randomFinal);
}


推荐阅读