1. 程式人生 > >innerHTML作用和用法

innerHTML作用和用法

innerHTML在JS是雙向功能:獲取物件的內容 或 向物件插入內容;
如:<div id="aa">這是內容</div>

我們可以通過 document.getElementById(‘aa’).innerHTML 來獲取id為aa的物件的內嵌內容;
也可以對某物件插入內容,如 document.getElementById(‘abc’).innerHTML=’這是被插入的內容’;
這樣就能向id為abc的物件插入內容。
例項:
1.獲取段落p的 innerHTML(html內容)

 <html>
    <head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/> <script type="text/javascript"> function getInnerHTML(){ alert(document.getElementById("test").innerHTML); } </script> </head> <body> <p
id="test">
<font color="#000">嗨豆殼 www.hi-docs.com</font></p> <input type="button" onclick="getInnerHTML()" value="點選" /> </body> </html>

2.設定段落p的 innerHTML(html內容)

<html>
        <head>
            <meta http-equiv="Content-Type" content
="text/html;charset=utf-8"/>
<script type="text/javascript"> function setInnerHTML(){ document.getElementById("test").innerHTML = "<strong>設定標籤的html內容</strong>"; } </script> </head> <body> <p id="test"><font color="#000">嗨豆殼 www.hi-docs.com</font></p> <input type="button" onclick="setInnerHTML()" value="點選" /> </body> </html>