Javascript 添加元素的好习惯

发布于 2024-12-12 18:35:02 字数 400 浏览 0 评论 0原文

我有一个由“parent”标识的空 div。我想在其中放入一个 p 元素。有两种方法:

第一种方法:

parent.innerHTML = "";
parent.innerHTML = "<p>My dummy text</p>";

第二种方法:

var myP = document.createElement('p');
var myText = document.createTextNode("My dummy text here");
myP.appendChild(myText);
parent.appendChild(myP);

就良好实践而言,这两种方法之间有区别吗?

谢谢!

I have a empty div identified by "parent". I want to put an p element inside of it. There are two methods:

Firts method:

parent.innerHTML = "";
parent.innerHTML = "<p>My dummy text</p>";

Second method:

var myP = document.createElement('p');
var myText = document.createTextNode("My dummy text here");
myP.appendChild(myText);
parent.appendChild(myP);

Is there a difference between the two methods when it comes to the good practices?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

笑叹一世浮沉 2024-12-19 18:35:02

当您打算添加纯文本(无事件侦听器)、无复杂属性值时,innerHTML 通常是一个不错的选择。

如果文本不包含任何 HTML 标记,则 textContentinnerText (IE) 是更好的选择,因为设置这些属性不会导致字符串被解析为HTML。

大量的 document.createElementappendChild 通常比设置 innerHTML 属性慢,尤其是当您比较 1000 倍的append-to-body 和1x .innerHTML

当您想要扩展内容未知的元素(它可能包含事件侦听器或用户修改的输入元素)时,建议使用appendChild。

When you're intending to add plain text (no event listeners), no complex attribute values, innerHTML is usually a good option.

If the text doesn't contain any HTML tags, textContent or innerText (IE) is a better choice, because setting these properties won't cause the string to be parsed as HTML.

Tons of document.createElement and appendChild are usually slower than setting the innerHTML property, especially when you're comparing 1000x append-to-body vs 1x .innerHTML.

It's recommended to use appendChild when you want to extend an element whose content is unknown (it may contain event listeners, or user-modified input elements).

旧人九事 2024-12-19 18:35:02

第一个选项可以删除该 DOM 上可能拥有的任何事件侦听器
而第二个选项则不会。

最好选择选项#2。

The 1st option can remove any event listeners you might have on that peice of the DOM
Whereas the second option will not.

Better to go with option #2.

姜生凉生 2024-12-19 18:35:02

这里有一些差异:

BAD

  • 这不是一个标准。它是 Microsoft 引入的专有属性(以及不太流行的outerHTML),并被其他浏览器制造商采用。
  • 由于它不是标准,因此它不应该在 XHTML 文档应在其下提供服务的 application/xhtml+xml MIME 类型下工作。 (Firefox 1.5 由于某种原因允许它改变了这一点)
  • InnerHTML 是一个字符串。 DOM 不是一个字符串,它是一个分层对象结构。
  • 在很多情况下,它会导致一些几乎难以辨认的代码,到处都有转义引号和加号,将数据附加到字符串中。

  • 它比 DOM 方法更快。快很多。

  • 它比 DOM 方法更简洁。

  • 它允许您获取任意标记块并将它们放入文档中,而无需解析它们。

Here some differences:

BAD

  • It's not a standard. It's a proprietary property that Microsoft introduced (along with the less popular outerHTML) that the other browser makers picked up.
  • Since it's not a standard, it's not supposed to work under the application/xhtml+xml MIME type that XHTML documents are supposed to be served under. (Firefox 1.5 changed this by allowing it for some reason)
  • InnerHTML is a string. The DOM is not a string, it's a hierarchal object structure.
  • It makes for some nearly illegible code in a lot of instances, with escaped quotes and plus signs all over the place appending data to the string.

GOOD

  • It's faster than DOM methods. By a lot.

  • It's less verbose than DOM methods.

  • It allows you to take arbitrary chunks of markup and drop them into a document without having to parse them.
不一样的天空 2024-12-19 18:35:02

如果您不小心,第一种方法可能会引入 XSS 漏洞。将其与示例中的常量字符串一起使用是安全的,但请考虑以下事项:

parent.innerHtml = "<p>" + document.getElementById('userInput').value + "</p>";

您刚刚将用户输入直接注入到 DOM 中。如果该输入包含脚本标记,那么您就已经被 XSS 攻击了。这是一个人为的示例,但您可以想象如何意外地从服务器端未转义的用户输入生成字符串并将其写入 DOM。

The first approach can introduce XSS holes, if you are not careful. Using it with constant strings like in your example is safe, but consider the following:

parent.innerHtml = "<p>" + document.getElementById('userInput').value + "</p>";

You've just injected user input directly into your DOM. If that input contains a script tag, then you've just been XSS'd. This is a contrived example, but you can imagine how you might accidentally generate a string from unescaped user input on the server side and write that into your DOM.

忘羡 2024-12-19 18:35:02

.innerHTML 是魔鬼。我们不使用它。

我们使用 DOM 方法是因为我们不应该使用内嵌的 JavaScript 片段。

.innerHTML 唯一有效的用例是跨浏览器合规性黑客和模板引擎。

如果你没有做其中任何一个,那么你应该使用 DOM4。

.innerHTML is the devil. We do not use it.

We use the DOM methods because we shouldn't be hacking around with in-line pieces of JavaScript.

The only valid use case for .innerHTML are cross browser compliance hacks and templating engines.

If your not doing either of those then your supposed to be using DOM4.

软糖 2024-12-19 18:35:02

来自 GWT UiBinder 文档

“浏览器更擅长通过填鸭式构建 DOM 结构将大的 HTML 字符串转换为 insideHTML 属性,而不是通过一堆 API 调用。”

我认为他们知道在这种情况下他们在说什么。

因此,除了它不会像 Rob Mayoff 在评论中提到的那样附加之外,使用innerHTML 可能会更快,特别是对于不太琐碎的情况。

From GWT UiBinder doc:

"Browsers are better at building DOM structures by cramming big strings of HTML into innerHTML attributes than by a bunch of API calls."

I think they know what they are talking about in this case.

So apart from the fact that it does not append as Rob Mayoff mentioned in the comment it's probably faster to go with innerHTML especially for less trivial cases.

如若梦似彩虹 2024-12-19 18:35:02

我看到的唯一区别是当您使用输入时。某些浏览器无法识别新输入已添加到表单中,并且在提交时不包含这些输入。

使用appendChild时不会出现此问题。因此,正确操作 DOM 和追加是一个很好的做法。

如果您认为创建每个元素并附加它的工作量太大,您可以考虑使用一些框架来使其更快。例如,jQuery 允许您使用 $(parent).html("

My dummy text here

") 并自动为您创建节点。

The only difference I see is when you're using inputs. Some browsers don't recognize that new inputs were added to a form and then, when submitted, don't include those inputs.

When using appendChild this problem does not occur. So, it is a good practice to manipulate DOM and append properly.

If you think it is too much work, create each element and append it, you may consider use some framework to make it faster. jQuery, for example, allows you to use $(parent).html("<p>My dummy text here</p>") and automatically create nodes for you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文