简体   繁体   English

使用 Javascript 编写 HTML 的正确方法是什么?

[英]What is the correct way to write HTML using Javascript?

It seems that experienced web developers frown upon using document.write() in JavaScript when writing dynamic HTML.似乎有经验的 Web 开发人员在编写动态 HTML 时不赞成在 JavaScript 中使用document.write()

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. document.write()只会在最初解析页面和创建 DOM 时起作用。 Once the browser gets to the closing </body> tag and the DOM is ready, you can't use document.write() anymore.一旦浏览器到达结束</body>标记并且 DOM 准备就绪,您就不能再使用document.write()了。

I wouldn't say using document.write() is correct or incorrect, it just depends on your situation.我不会说使用document.write()是正确还是不正确,这取决于您的情况。 In some cases you just need to have document.write() to accomplish the task.在某些情况下,您只需要使用document.write()即可完成任务。 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> ): DOM 准备就绪后,您有两种方法可以插入动态 HTML(假设我们要将新的 HTML 插入到<div id="node-id"></div> ):

  1. Using innerHTML on a node:在节点上使用innerHTML:

     var node = document.getElementById('node-id'); node.innerHTML('<p>some dynamic html</p>');
  2. Using DOM methods:使用 DOM 方法:

     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.使用 DOM API 方法可能是最纯粹的做事方式,但innerHTML已被证明要快得多,并且在 JavaScript 库(如 jQuery)中使用。

Note: The <script> will have to be inside your <body> tag for this to work.注意: <script>必须在你的<body>标签内才能工作。

document.write() doesn't work with XHTML. document.write()不适用于 XHTML。 It's executed after the page has finished loading and does nothing more than write out a string of HTML.它在页面加载完成执行只是写出一串 HTML。

Since the actual in-memory representation of HTML is the DOM, the best way to update a given page is to manipulate the DOM directly.由于 HTML 在内存中的实际表示是 DOM,因此更新给定页面的最佳方法是直接操作 DOM。

The way you'd go about doing this would be to programmatically create your nodes and then attach them to an existing place in the DOM.您这样做的方法是以编程方式创建您的节点,然后将它们附加到 DOM 中的现有位置。 For [purposes of a contrived] example, assuming that I've got a div element maintaining an ID attribute of "header," then I could introduce some dynamic text by doing this:对于[人为的]示例,假设我有一个div元素维护“header”的ID属性,那么我可以通过这样做来引入一些动态文本:

// create my text
var sHeader = document.createTextNode('Hello world!');

// create an element for the text and append it
var spanHeader = document.createElement('span');
spanHeader.appendChild(sHeader);

// grab a reference to the div header
var divHeader = document.getElementById('header');

// append the new element to the header
divHeader.appendChild(spanHeader);
  1. DOM methods, as outlined by Tom. DOM 方法,如 Tom 所述。

  2. innerHTML, as mentioned by iHunger. innerHTML,如 iHunger 所述。

DOM methods are highly preferable to strings for setting attributes and content.在设置属性和内容方面,DOM 方法比字符串更可取。 If you ever find yourself writing innerHTML= '<a href="'+path+'">'+text+'</a>' you're actually creating new cross-site-scripting security holes on the client side, which is a bit sad if you've spent any time securing your server-side.如果您发现自己编写了innerHTML= '<a href="'+path+'">'+text+'</a>'那么您实际上是在客户端创建了新的跨站点脚本安全漏洞,这是一个如果您花了任何时间保护您的服务器端,有点难过。

DOM methods are traditionally described as 'slow' compared to innerHTML.与innerHTML 相比,DOM 方法传统上被描述为“慢”。 But this isn't really the whole story.但这并不是故事的全部。 What is slow is inserting a lot of child nodes:缓慢的是插入大量子节点:

 for (var i= 0; i<1000; i++)
     div.parentNode.insertBefore(document.createElement('div'), div);

This translates to a load of work for the DOM finding the right place in its nodelist to insert the element, moving the other child nodes up, inserting the new node, updating the pointers, and so on.这意味着 DOM 需要在其节点列表中找到正确的位置来插入元素、向上移动其他子节点、插入新节点、更新指针等工作负载。

Setting an existing attribute's value, or a text node's data, on the other hand, is very fast;另一方面,设置现有属性的值或文本节点的数据非常快; you just change a string pointer and that's it.您只需更改一个字符串指针即可。 This is going to be much faster than serialising the parent with innerHTML, changing it, and parsing it back in (and won't lose your unserialisable data like event handlers, JS references and form values).这将比使用 innerHTML 序列化父级、更改它并重新解析它要快得多(并且不会丢失不可序列化的数据,如事件处理程序、JS 引用和表单值)。

There are techniques to do DOM manipulations without so much slow childNodes walking.有一些技术可以在没有如此缓慢的 childNodes 行走的情况下进行 DOM 操作。 In particular, be aware of the possibilities of cloneNode , and using DocumentFragment .特别要注意cloneNode和使用DocumentFragment的可能性。 But sometimes innerHTML really is quicker.但有时innerHTML 确实更快。 You can still get the best of both worlds by using innerHTML to write your basic structure with placeholders for attribute values and text content, which you then fill in afterwards using DOM.您仍然可以通过使用 innerHTML 编写带有属性值和文本内容占位符的基本结构,然后使用 DOM 填充它们,从而获得两全其美的效果。 This saves you having to write your own escapehtml() function to get around the escaping/security problems mentioned above.这使您不必编写自己的escapehtml()函数来解决上面提到的转义/安全问题。

Perhaps a good idea is to use jQuery in this case.也许在这种情况下使用 jQuery 是个好主意。 It provides handy functionality and you can do things like this:它提供了方便的功能,您可以执行以下操作:

$('div').html('<b>Test</b>');

Take a look at http://docs.jquery.com/Attributes/html#val for more information.查看http://docs.jquery.com/Attributes/html#val了解更多信息。

您可以改为更改页面上元素的innerHTMLouterHTML

I'm not particularly great at JavaScript or its best practices, but document.write() along with innerHtml() basically allows you to write out strings that may or may not be valid HTML;我不是特别擅长 JavaScript 或其最佳实践,但是document.write()innerHtml()基本上允许您写出可能是或可能不是有效 HTML 的字符串; it's just characters.这只是字符。 By using the DOM, you ensure proper, standards-compliant HTML that will keep your page from breaking via plainly bad HTML.通过使用 DOM,您可以确保正确的、符合标准的 HTML,这将防止您的页面因明显错误的 HTML 被破坏。

And, as Tom mentioned, JavaScript is done after the page is loaded;而且,正如 Tom 所说,JavaScript 在页面加载后完成; it'd probably be a better practice to have the initial setup for your page to be done via standard HTML (via .html files or whatever your server does [ie php]).通过标准 HTML(通过 .html 文件或您的服务器所做的任何事情 [即 php])完成页面的初始设置可能是更好的做法。

element.InnerHtml= allmycontent : will re-write everything inside the element. element.InnerHtml= allmycontent :将重写元素内的所有内容。 You must use a variable let allmycontent="this is what I want to print inside this element" to store the whole content you want inside this element.您必须使用一个变量let allmycontent="this is what I want to print inside this element"来存储您想要在该元素中的全部内容。 If not each time you will call this function, the content of your element will be erased and replace with the last call you made of it.如果不是每次调用此函数时,元素的内容都将被删除并替换为您最后一次调用它的内容。

document.write() : can be use several times, each time the content will be printed where the call is made on the page. document.write() :可以多次使用,每次都会在页面调用的地方打印内容。

But be aware: document.write() method is only useful for inserting content at page creation .但请注意: document.write()方法用于在页面创建时插入内容。 So use it for not repeating when having a lot of data to write like a catalogue of products or images.因此,当需要编写大量数据(如产品或图像目录)时,请使用它来避免重复。

Here a simple example: all your li for your aside menu are stored in an array "tab", you can create a js script with the script tag directly into the html page and then use the write method in an iterative function where you want to insert those li on the page.这里有一个简单的例子:你的aside menu的所有li都存储在一个数组“tab”中,你可以创建一个带有script标签的js脚本直接进入html页面,然后在你想要的迭代函数中使用write方法在页面上插入那些 li。

<script type="text/javascript">
document.write("<ul>");
for (var i=0; i<=tab.length; i++){
    document.write(tab[i]);
    }document.write("</ul>");
</script>`

This works because Js is interpreted in a linear way during the loading.这是有效的,因为在加载过程中以线性方式解释Js。 So make sure your script is at the right place in your html page.You can also use an external Js file, but then again you must declare it at the place where you want it to be interpreted.因此,请确保您的脚本位于 html 页面中的正确位置。您也可以使用外部 Js 文件,但您必须再次在您希望解释它的位置声明它。

For this reason, document.write cannot be called for writing something on your page as a result of a "user interaction" (like click or hover), because then the DOM has been created and write method will, like said above, write a new page (purge the actual execution stack and start a new stack and a new DOM tree).因此,由于“用户交互” (例如单击或悬停),不能调用document.write在您的页面上写一些东西,因为那时 DOM 已经创建,并且 write 方法将,如上所述,写一个新页面(清除实际执行堆栈并启动新堆栈和新 DOM 树)。 In this case use:在这种情况下使用:

element.innerHTML=("Myfullcontent");

To learn more about document's methods: open your console: document;要了解有关文档方法的更多信息:打开您的控制台: document; then open: __proto__: HTMLDocumentPrototype然后打开: __proto__: HTMLDocumentPrototype

You'll see the function property "write" in the document object.您将在文档对象中看到函数属性“write”。 You can also use document.writeln which add a new line at each statement.您还可以使用document.writeln在每个语句中添加一个新行。 To learn more about a function/method, just write its name into the console with no parenthesis: document.write;要了解有关函数/方法的更多信息,只需将其名称写入控制台,不带括号: document.write; The console will return a description instead of calling it.控制台将返回一个描述而不是调用它。

There are many ways to write html with JavaScript.有很多方法可以用 JavaScript 编写 html。

document.write is only useful when you want to write to page before it has actually loaded. document.write 仅当您想在页面实际加载之前写入页面时才有用。 If you use document.write() after the page has loaded (at onload event) it will create new page and overwrite the old content.如果在页面加载后(在 onload 事件中)使用 document.write() ,它将创建新页面并覆盖旧内容。 Also it doesn't work with XML, that includes XHTML.它也不适用于 XML,包括 XHTML。

From other hand other methods can't be used before DOM has been created (page loaded), because they work directly with DOM.另一方面,在创建 DOM(页面加载)之前不能使用其他方法,因为它们直接使用 DOM。

These methods are:这些方法是:

  • node.innerHTML = "Whatever"; node.innerHTML = "随便";
  • document.createElement('div'); document.createElement('div'); and node.appendChild(), etc..和 node.appendChild() 等。

In most cases node.innerHTML is better since it's faster then DOM functions.在大多数情况下,node.innerHTML 更好,因为它比 DOM 函数更快。 Most of the time it also make code more readable and smaller.大多数情况下,它还使代码更具可读性和更小。

Surely the best way is to avoid doing any heavy HTML creation in your JavaScript at all?最好的方法当然是完全避免在 JavaScript 中进行任何繁重的 HTML创建 The markup sent down from the server ought to contain the bulk of it, which you can then manipulate, using CSS rather than brute force removing/replacing elements, if at all possible.从服务器发送下来的标记应该包含其中的大部分,然后您可以使用 CSS 而不是蛮力删除/替换元素(如果可能的话)进行操作。

This doesn't apply if you're doing something "clever" like emulating a widget system.如果您正在做一些“聪明”的事情,例如模拟小部件系统,则这不适用。

The document.write method is very limited. document.write 方法非常有限。 You can only use it before the page has finished loading.您只能在页面加载完成之前使用它。 You can't use it to update the contents of a loaded page.您不能使用它来更新已加载页面的内容。

What you probably want is innerHTML .您可能想要的是innerHTML

I think you should use, instead of document.write , DOM JavaScript API like document.createElement , .createTextNode , .appendChild and similar.我认为你应该使用 DOM JavaScript API,而不是document.write ,比如document.createElement.createTextNode.appendChild等。 Safe and almost cross browser.安全且几乎跨浏览器。

ihunger's outerHTML is not cross browser, it's IE only. ihunger 的outerHTML不是跨浏览器,它只是IE。

Use jquery, look how easy it is:使用 jquery,看看它是多么容易:

    var a = '<h1> this is some html </h1>';
    $("#results").html(a);

       //html
    <div id="results"> </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 编写这个javascript函数的正确方法是什么? - What is the correct way to write this javascript function? 有什么比用JavaScript编写document.write更好的HTML编写方法? - What is a better way to write HTML than document.write in JavaScript? 使用 CSS 和 Javascript 向 HTML DOM 对象添加动画的正确方法是什么? - What is the correct way of adding animation to an HTML DOM object with CSS and Javascript? 在构建html时,在javascript中支持撇号的正确方法是什么? - What is the correct way to support apostrophes in javascript when building up html? 通过JavaScript引用HTML元素的正确方法是什么? - What is the correct way to refer to HTML elements via JavaScript? HTML5 在锚点中使用 Javascript 的正确方法是什么? - What is the correct way in HTML5 to use Javascript in anchors? 使用Javascript中的模块模式调用内部函数的正确方法是什么 - What is the correct way of calling an internal function using the module pattern in Javascript 在 Angular 中编写可链接函数的正确方法是什么? - What is the correct way to write chainable function in Angular? 在没有浏览器进行与时区相关的任何调整的情况下,在 JavaScript 中写入日期的正确方法是什么 - What is the correct way to write a Date in JavaScript without having browsers do any adjustments related to timezone 在html中包含脚本的正确方法是什么 - what is the correct way to include a script in html
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM