javascript - 从数组中设置元素的 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);
}
解决方案
我设法弄清楚了,我定位了我的元素,然后使用我的数组中的值添加了一个类!
这是代码(抱歉评论是法语)
// 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);
}
推荐阅读
- machine-learning - scikit-learn GradientBoostingRegressor 的“init”参数是否定义了基本估计量?
- javascript - AJAX 获取请求按钮
- java - 访问数组的数组内的元素
- spring - jboss eap 错误 org.jboss.jca.adapters.jdbc.jdk8.WrappedConnectionJDK8 无法转换为 oracle.jdbc.internal.OracleConnection
- java - 如何使用 selenium webdriver 和页面对象模型解决 java.lang.NullPointerException
- java - 无法使用硒(java)单击此按钮
- sql - 具有多个表的数据库查询
- php - 如何使用wordpress url中的变量进行路由?
- python - Python requests-html:使用 cookie 渲染 html
- python - 从 Django 中的数据库获取用户详细信息