使用Javascript编写HTML的正确方法是什么? [英] What is the correct way to write HTML using Javascript?

查看:136
本文介绍了使用Javascript编写HTML的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一些文章中看到,在编写动态HTML时,人们对使用JavaScript中的 document.write()产生了不满。



这是为什么?什么是正确的方式?

解决方案 > document.write() 只会在最初解析页面并创建DOM时起作用。一旦浏览器到达结束< / body> 标记并且DOM已准备好,您就不能使用 document.write() code>>。

我不会说使用 document.write()是正确的还是不正确的,这取决于你的情况。在某些情况下,您只需要 document.write()来完成任务。看看Google分析如何被注入到大多数网站中。

在DOM准备好之后,您有两种插入动态HTML的方法(假设我们要将新的HTML插入< div id =node-id>< / div> ):


  1. 在节点上使用innerHTML:

      var node = document.getElementById('node-id'); 
    node.innerHTML('< p>一些动态html< / p>');


  2. 使用DOM方法:

      var node = document.getElementById('node-id'); 
    var newNode = document.createElement('p');
    newNode.appendChild(document.createTextNode('some dynamic html'));
    node.appendChild(newNode);


使用DOM API方法可能是纯粹主义者方式来做东西,但 innerHTML 已被证明更快,并且在JavaScript库(如jQuery)中引擎盖下。



注意:< script> 必须位于< body> 标签以便使用。


I see in some posts that people frown upon using document.write() in javascript when writing dynamic HTML.

Why is this? and what is the correct way?

解决方案

document.write() will only work while the page is being originally parsed and the DOM is being created. Once the browser gets to the closing </body> tag and the DOM is ready, you can't use document.write() anymore.

I wouldn't say using document.write() is correct or incorrect, it just depends on your situation. In some cases you just need to have document.write() to accomplish the task. Look at how Google analytics gets injected into most websites.

After DOM ready, you have two ways to insert dynamic HTML (assuming we are going to insert new HTML into <div id="node-id"></div>):

  1. Using innerHTML on a node:

    var node = document.getElementById('node-id');
    node.innerHTML('<p>some dynamic html</p>');
    

  2. Using DOM methods:

    var node = document.getElementById('node-id');
    var newNode = document.createElement('p');
    newNode.appendChild(document.createTextNode('some dynamic html'));
    node.appendChild(newNode);
    

Using the DOM API methods might be the purist way to do stuff, but innerHTML has been proven to be much faster and is used under the hood in JavaScript libraries such as jQuery.

Note: The <script> will have to be inside your <body> tag for this to work.

这篇关于使用Javascript编写HTML的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆