js動態建立元素,並控制元素樣式

火雲邪神發表於2018-08-23
 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            padding:30px;
        }
    </style>
</head>
<body>
    <div id="oo">
            <!-- <div><i>語</i><span></span></div>
            <div><i>語</i><span></span></div>
            <div><i>語</i><span></span></div> -->
    </div>

    <script>

        var kemu = [
            {ke:'數',name:'數學'},
            {ke:'語',name:'語文'},
            {ke:'英',name:'英語'}
        ]
        new function () {
        kemu.forEach(function (item,index) {
            var div = document.createElement('div');
                div.innerHTML += `<i>${item.ke}</i><span>${item.name}</span>`;
                oo.appendChild(div);
                function changeColor (x,y,z) {
                    switch (index) {
                    case 0 : 
                    (x.childNodes[0].style.color = 'red',
                    x.childNodes[1].style.backgroundColor = 'red');  break;
                    case 1 : 
                    (y.childNodes[0].style.color = 'blue',
                    y.childNodes[1].style.backgroundColor = 'blue');  break;
                    case 2 : 
                    (z.childNodes[0].style.color = 'green',
                    z.childNodes[1].style.backgroundColor = 'green');  break;
                }
                }
                changeColor(oo.childNodes[3],oo.childNodes[4],oo.childNodes[5]);
        });
        
        }

    </script>
</body>
</html>

複製程式碼

相關文章