jQuery:创建新元素时,我需要结束标签吗?
var $div = $('<div class="error">').appendTo($('#header'));
创建新元素并将其添加到 DOM 时,是否需要结束标签?为什么或为什么不?如果我将内容放入我正在创建的标签中,是否只需要结束标签?像这样:
var $div = $('<div class="error"> Error-Homie! </div>').appendTo($('#header'));
或者我可以创建一个包含内容的元素,但省略结束标签吗?好的?坏的?
var $div = $('<div class="error">').appendTo($('#header'));
var $div = $('<div class="error">').appendTo($('#header'));
When creating new elements and adding them to the DOM, do you need the ending tag? why or why not? Do I only need the ending tag if i'm placing content into the tag i'm creating? like so:
var $div = $('<div class="error"> Error-Homie! </div>').appendTo($('#header'));
or could I create an element with content in it, but leave out the ending tag? Good? Bad?
var $div = $('<div class="error">').appendTo($('#header'));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
虽然如果您不使用关闭标签(或至少自行关闭标签),它可能会起作用,但是 您应该添加一个结束标签(自关闭)(如上所述,为了跨平台兼容性):
这就是方式jQuery 创建元素:
顺便提一句。您还可以将数据作为第二个参数传递:
Although it may work if you don't use a closing tag (or at least self close the tag), you should add a closing tag (self-close) (as mentioned, for cross-platform compatibility):
This is how jQuery creates the elements:
Btw. you can also pass the data as second parameter:
您需要结束标签: http://api.jquery.com/appendTo/ 例如
它应该也是
和不是
you need the ending tag : http://api.jquery.com/appendTo/ for example
it should also be
and not
你也许可以这样做
you can probably do it like this
您始终需要结束标记才能拥有正确的 html。
但事实上,大多数浏览器都会忽略此类错误。不过,没有理由偷懒,您不应该依赖浏览器的容忍度来让代码正常工作。这种容忍度是为了能够显示有一些错误的站点,而不是为了警告故意错误的代码。
You always need the ending tag to have proper html.
But it is a fact that the majority of browsers let such mistakes slip. It's no reason to be lazy, though, you should not rely on the browsers' tolerance for your code to work. This tolerance is there to be able to display sites with a few mistakes, not to caution deliberately incorrect code.