批量创建标签

2022-03-15  本文已影响0人  心存美好
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        div {
            /* float:left; */
            display: inline-block;
            width: 50px;
            height: 50px;
            margin: 10px;
            background-color: red;
        }
    </style>
</head>

<body>
    <p><input type="button" value='生成10个div' id='but'></p>


    <script>
        let istrue = false;   //拦截只执行一次
        let oBut = document.getElementById('but');
        oBut.onclick = function () {
            if (istrue) {
                return     //拦截只执行一次
            }
            let frag = document.createDocumentFragment()//文档片段,用于加到页面上
            for (let i = 0; i < 10; i++) {
                let dom = document.createElement('div') //创建标签
                frag.appendChild(dom)
            }
            document.body.appendChild(frag)
            istrue = true;
        }



    </script>

</body>

</html>
上一篇 下一篇

猜你喜欢

热点阅读