js小练习demo(蓝桥杯复习demo)

借助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];
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值