借助csdn平台记录一下我的js学习写的小demo 4.8蓝桥杯比赛希望可以取得好成绩 也供你们参考 如果代码有可以改进的地方 请尽情评论
实现功能:让数组内的数字随机生成 颜色数字内的颜色 然后write在body上
第一版写法
let arr = [1, 2, 3, 4];
const colorList = ["red", "green", "skyblue"];
this.create('div', arr)
function create(element, arr) {
arr.map((item) => {
var div = document.createElement(element)
div.setAttribute("id", `div_${item}`);
div.setAttribute("style", `color:${math()};background:#fff`);
div.innerHTML = item
document.body.appendChild(div)
})
}
var divclick = Array.from(document.querySelectorAll('div'))
divclick.map((item, index) => {
item.addEventListener('click', function (e) {
divclick.splice(index, 1)
e.target.remove()
console.log(e);
})
})
function math() {
let colorMath = Math.floor(Math.random() * colorList.length + 1) - 1;
let color;
console.log(colorMath);
for (const num in colorList) {
if (num == colorMath)
color = colorList[num]
}
return color;
}
然后今天看这个demo的时候简化了一下
简化后的代码:
const arr = [1, 2, 3, 4];
const colorList = ["red", "green", "skyblue"];
arr.forEach((item) => {
const div = document.createElement('div');
div.id = `div_${item}`;
div.style.color = math();
div.style.background = "#fff";
div.textContent = item;
document.body.appendChild(div);
div.addEventListener('click', () => {
div.remove();
});
});
function math() {
const colorMath = Math.floor(Math.random() * colorList.length);
return colorList[colorMath];
}