`
tongmin_tsai
  • 浏览: 11417 次
  • 性别: Icon_minigender_1
  • 来自: 惠州
社区版块
存档分类
最新评论

innerText与innerHTML

阅读更多

在DOM中,如果要在一个标签上面加入文字,则必须用object.appendChild(document.createTextNode("你要加入的文字"));让人感觉非常麻烦,代码冗长,于是乎,就有了用object.innerText = "你要加入的文字";这一种写法.是代码更简洁,更易于理解.innerText会自动把大于号,小于号等等的HTML元素都进行编码,所以不必担心显示的问题,如果确实要用HTML方式的,请使用innerHTML.下面的代码摘自JS高级程序设计一书:

innerText:

<html>
    <head>
        <title>InnerText Example</title>
        <style type="text/css">
            div.special {
                background-color: red;
                padding: 10px;
            }
        </style>
        <script type="text/javascript">
            function useInnerText() {
                var oDiv = document.getElementById("div1");
                oDiv.innerText = oDiv.innerText;
            }
        </script>
 
    </head>
    <body>
        <div id="div1" class="special"><b>Hello</b> world</div>
        <input type="button" value="Use InnerText" onclick="useInnerText()" />
        <p><strong>Note: </strong> Firefox does not support the <code>innerText</code> property so this example will fail.</p>
    </body>
</html>

 

innerHTML:

<html>
    <head>
        <title>InnerHTML Example</title>
        <style type="text/css">
            div.special {
                background-color: red;
                padding: 10px;
            }
        </style>
        <script type="text/javascript">
            function useInnerHTML() {
                var oDiv = document.getElementById("div1");
                oDiv.innerHTML = "<b>Hello</b> world";
            }
        </script>
 
    </head>
    <body>
        <div id="div1" class="special">This is my original text</div>
        <input type="button" value="Use InnerHTML" onclick="useInnerHTML()" />
    </body>
</html>

 

此外,我们还可以通过这2个属性来获取元素的内容:

 

  • 大小: 22.8 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics