2015年8月26日 星期三

動態新增Div與文字(JavaScript範例) -- 20150826

步驟如下:

1.開啟一個全新的HTML網頁。
2.將下面兩段程式碼放入新網頁中。
3.執行後,可以看見效果。



-----(放置head標籤內)-----------------------------


<script type="text/javascript">

    function GreateParagraph(t) {
        var body = document.getElementsByTagName("body")[0];
        var para = document.createElement("div");
        //動態新增一段落文字,可修改createElement內的元件標籤,如:createElement("p")
        var ptext = document.createTextNode(t);

        para.appendChild(ptext);
        body.appendChild(para);

    }

</script>



------(放置body標籤內)-------------------------------------------

<form id="form1" name="form1" method="get" action="">

文字:<input type="text" name="t" /> 
 <input type="button" value="產生文字段落" onclick="GreateParagraph(this.form.t.value);" />
                                                          
</form>

-------------------------------------------------------------------------------



※使用getElementsByTagName( )取得HTML標籤成為物件。
   使用getElementById( )取得HTML標籤中以id識別的元件成為物件。