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

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

问题描述

相关的答案 https://stackoverflow.com/a/10619477/1076753 来清理元素更好使用

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

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

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

官方的 API文档表示,为确保跨平台兼容性,片段必须格式良好。可以包含其他元素的标签应与结束标记配对:

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

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

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

因此,最后使用前两个选项之一是错误的 div ????????字节更短。



一旦您开始考虑可读性和其他不那么实际的考虑因素,它主要是一个意见问题。


因此,最后使用div的前两个选项之一是错误的?


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


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

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

or

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

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

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>" );

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

解决方案

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.

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

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

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

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