众所周知,我们可以通过以下代码创建新元素:
$('<div/>', {
style: 'display: inline-block;'
})
但我想知道,是否有关于如何创建它们的规则?
我应该像这样作为第一个参数(标签名称)字符串传递 -- <div/>
?或者也许像这样 - <div>
?或者甚至像这样-div
?
从文档中我不清楚。
最佳答案
documentation对此其实是很清楚的。它期望 htmlString
:
A string is designated htmlString in jQuery documentation when it is used to represent one or more DOM elements, typically to be created and inserted in the document. When passed as an argument of the jQuery() function, the string is identified as HTML if it starts with ) and is parsed as such until the final > character.
所以你不能使用div
因为这实际上会搜索所有现有的 <div>
在你的 DOM 中。
和it also says :
When the parameter has a single tag (with optional closing tag or quick-closing) — $( "
<img />
" ) or $( "<img>
" ), $( "<a></a>
" ) or $( "<a>
" ) — jQuery creates the element using the native JavaScript .createElement() function.
那里清楚地表明关闭标签是可选的。所以 <div>
之一或<div />
很好。
关于javascript - 如何正确命名以编程方式创建的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38997409/