Javascript DocumentFragment 文档片段

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <style type="text/css">
        #main,#control{width:200px;margin:0px auto;background-color:Red;}
        #control{background-color:Blue;}
    </style>
    <script type="text/javascript">
        /*
        说明:
            1.DocumentFragment类型的nodeType=11
            2.document.createDocumentFragment();
            3.DocumentFragment 可以起到临时容器的作用,
              将要追加的元素 加入DocumentFragment对象中,
              最后将DocumentFragment对象插入到dom树指定节点位置后,
              DocumentFragment对象消失。不占用dom树节点位置。
            4.在批量添加元素时使用,可以提高效率
        */
        window.onload = function () {
            document.getElementById("btn").onclick = function () {
                var documentFrag = document.createDocumentFragment();
                for (var i = 0; i < 20; i++) {
                    var btnTmp = document.createElement("input");
                    btnTmp.type = "button";
                    btnTmp.setAttribute("value", "按钮" + i);
                    btnTmp.onclick = function () {
                        alert(this.attributes.getNamedItem("value").nodeValue);
                    }
                    documentFrag.appendChild(btnTmp);
                }
                document.getElementById("main").appendChild(documentFrag);
            }
        }
    </script>
</head>
<body>
    <div id="control">
        <input id="btn" type="button" value="批量添加按钮" onclick="appendButtons()" />
    </div>
    <div id="main"></div>
</body>
</html>

你可能感兴趣的:(Javascript DocumentFragment 文档片段)