哪个是使用 jQuery 创建新元素的正确或更好的方法? [英] Which is the correct or better way to create a new element with jQuery?

查看:28
本文介绍了哪个是使用 jQuery 创建新元素的正确或更好的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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"

这篇关于哪个是使用 jQuery 创建新元素的正确或更好的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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