zoukankan      html  css  js  c++  java
  • JavaScript tips:innerHTML与document.write的差异

    1、innerHTML:

    (1)作用:覆盖调用该方法的元素的内容。内容可以添加文本节点或者元素节点。

    (2)代码:

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title></title>
      </head>
      <body>
        <div id="test">修改前</div>
        <script>
            var test = document.getElementById("test");
            test.innerHTML = "修改后"
        </script>
      </body>
    </html>    

    2、document.write:

    作用:

    (1)在文档加载完毕前,调用document.write会在调用处输出流。

    可以观察到三个hello world

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title></title>
      </head>
      <body>
        <script>
            document.write("<p>hello world</p>");
        </script>
        <p>hello world</p>
        <script>
            document.write("<p>hello world</p>");
        </script>
      </body>
    </html>

    (2)在文档加载完毕后,会调用document.open方法,重新创建document覆盖已经加载过的document,此时调用document.write会在新的document输出流。

    只能够看到一个hello world:

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title></title>
      </head>
      <body>
        <p>hello world</p>
        <script>
           window.onload = function(){
               document.write("<p>hello world</p>");
           }        
        </script>
      </body>
    </html>    
  • 相关阅读:
    js 实现加入收藏/加入首页功能
    js 获取网页宽/高度
    js 飞机大战
    js 实现分享功能
    前端开发的工具,库和资源总结
    网站更新后客户端缓存问题
    js 实现图片无限横向滚动效果
    js 实现 文字打印效果
    js 构造函数创建钟表
    Css3 实现关键帧动画
  • 原文地址:https://www.cnblogs.com/niconicohang/p/6613853.html
Copyright © 2011-2022 走看看