哪个是使用 jQuery 创建新元素的正确或更好的方法?

2022-01-18 00:00:00 tags frameworks jquery javascript html

与https://stackoverflow.com/a/10619477/1076753的答案相关,清除一个元素更好使用

Related to the answer https://stackoverflow.com/a/10619477/1076753 to cleate an element is better to use

$("<div>", {id: "foo", class: "a"});

$("<div />", {id: "foo", class: "a"});

它们都有效,但哪个更好或更正确?

They both works, but which is better or correct to use?

官方的API Documentation说要保证跨平台的兼容性,snippet一定要好-形成.可以包含其他元素的标签应与结束标签配对:

The official API Documentation says that to ensure cross-platform compatibility, the snippet must be well-formed. Tags that can contain other elements should be paired with a closing tag:

$( "<a href='http://jquery.com'></a>" );

虽然不能包含元素的标签可能会被快速关闭:

while Tags that cannot contain elements may be quick-closed or not:

$( "<img>" );
$( "<input>" );

那么,最后将前两个选项之一用于 div 是错误的吗?

So, at the end it's wrong to use one of the first two options for a div?

推荐答案

如果你只使用易于衡量的指标:第一个更好,因为它短 2 个字节.

If you go solely by metrics that can be easily measured: The first is better because it is 2 bytes shorter.

一旦您开始考虑可读性和其他不太具体的考虑因素,它在很大程度上就变成了一个见仁见智的问题.

Once you start accounting for readability and other less tangible considerations, it becomes largely a matter of opinion.

那么,最后将前两个选项之一用于 div 是错误的吗?

So, at the end it's wrong to use one of the first two options for a div?

不,该部分仅适用于如果 HTML 比没有属性的单个标记更复杂"

No, that section only applies "If the HTML is more complex than a single tag without attributes"

相关文章