[英]How do you create an element with jQuery?
Do you create it like this: $('<div />')
or $('<div></div>')
你是这样创建的: $('<div />')
或$('<div></div>')
Is that how you create an element? 这是你如何创建一个元素? Thanks. 谢谢。
Either way works just fine. 无论哪种方式都可以。 Just don't forget to insert in the dom - you can use appendTo(selector)
. 只是不要忘记在dom中插入 - 你可以使用appendTo(selector)
。
var $my_elem = $("<div/>").appendTo(document.body);
var $my_elem = $("<div class='abc'></div>").appendTo(document.body);
Then you have $my_elem
represending the inserted element. 然后你有$my_elem
代表插入的元素。
$('YOUR SELECTOR').append('<div />');
The <div />
will create a <div></div>
<div />
将创建一个<div></div>
You can include classes, id's and other attributes, jQuery should figure it out and rap it up. 你可以包括类,id和其他属性,jQuery应该弄明白并说出来。
I included use of the append function because you are probably going to want to insert it somewhere. 我包括使用append函数,因为你可能想要在某处插入它。 There is a number of similar functions you could use instead. 您可以使用许多类似的功能。
Looking at the jQuery source code , it looks like anything matching the regular expression /^<(\\w+)\\s*\\/?>(?:<\\/\\1>)?$/
will be interpreted as a "single tag" and passed directly to document.createElement
(assuming no context
is specified). 看看jQuery源代码 ,它看起来像正则表达式匹配的任何东西/^<(\\w+)\\s*\\/?>(?:<\\/\\1>)?$/
将被解释为“单个标签“并直接传递给document.createElement
(假设没有指定context
)。 Therefore, at least in the current implementation, there's no difference (behavior or performance) between the various formats. 因此,至少在当前实现中,各种格式之间没有差异(行为或性能)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.