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>

猜你喜欢

转载自blog.csdn.net/qq_34663267/article/details/82431093
今日推荐