如何通过javascript动态添加标签?

JavaScript019

如何通过javascript动态添加标签?,第1张

可以直接用document.getElementById("divid").innerHTML = "<p>内容</p>"的方式来写。

多个可以循环进行处理。

假设段落文本是个数组:array。

可以通过for (var i = 0i <array.lengthi++) {document.getElementById("divid").innerHTML = "<p>"+array[i]+"</p>"}的方式进行处理。

延展:

如果段落过多,直接使用 div.appendChild方法会不段刷新DIV对象,影响运行速度。

正确的方法应该使用 document对象的碎片方法。

document.createDocumentFragment 容器,最后再将这些碎片返回给DIV对象比较合理,例如:

var strArrayList=[]// 创建一个段落文本数组对象,这些段落文本可能是100个也可能是1000个。

strArrayList[0]='数据111.......'

strArrayList[1]='数据.......'

strArrayList[2]='数据.......'

strArrayList[3]='数据.......'

strArrayList[4]='数据.......'

//...数据n.....

var div=document.getElementById('div1')//获得DIV对象。

var f=document.createDocumentFragment()//创建碎片对象。

for(var i=0i<strArrayList.lengthi++){

var p=document.createElement('P')//动态创建P标签。

p.appendChild(document.createTextNode(strArrayList[i]))//段落字符串。

f.appendChild(p)//附加到碎片对象中。

}

div.appendChild(f)//最后返给DIV对象。

<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>RunJS</title>

    <script id="jquery_180" type="text/javascript" class="library" src="/js/sandbox/jquery/jquery-1.8.0.min.js"></script>

    <script type="text/javascript">

        function c(a, b) {

            var ap = a.parents("#1option")

            if (!b) {

                ap.toggle()

            } else {

                ap.find(b).toggle()

            }

        }

        $(function() {

            $(":button[value='添加']").click(function() {

                $("body").append($("textarea").val())

            })

        })

    </script>

</head>

<body>

    <input type="button" value="添加" />

    <textarea style="display:none">

        <div id="1option" style="width:800pxheight:170pxdisplay:block">

            <div id="first">

                <div style="width:800pxheight:20pxbackground-color:#EDEDED">

                    <div id="legend" style="float:left">c</div>

                    <div class="fa fa-times" id="close12" onclick="c($(this))" style="float: rightcursor:pointer">x</div>

                    <div class="fa fa-arrows-alt" id="d1toBig" onclick="c($(this),'#seconddiv')" style="float:rightmargin-right:5px">s</div>

                    <div class="fa fa-wikipedia-w" id="d1To7day" style="float:rightmargin-right:5pxcursor:pointer"></div>

                </div>

                <div id="container" style="width:800pxheight:150pxbackground-color:#FFFFFF"></div>

            </div>

            <div id="seconddiv" style="height:900pxwidth:1580pxz-index: 9999 display:none position: fixed left: 10px top: 15pxbackground-color: #2E8B57">

                <div class="fa fa-times" id="close12" onclick="c($(this),'#seconddiv')" style="float: rightmargin-right:40pxmargin-top:7pxcursor:pointer"></div>

                <div id="newdiv1" style="width:1500pxheight:700pxmargin-left:40pxmargin-top:30px"></div>

            </div>

        </div>

    </textarea>

</body>

</html>