jQuery:创建新元素时,是否需要结束标签? [英] jQuery: When creating a new element, do I need the ending tag?
问题描述
var $div = $('<div class="error">').appendTo($('#header'));
在创建新元素并将它们添加到 DOM 时,是否需要结束标记?为什么或者为什么不?如果我将内容放入我正在创建的标签中,我是否只需要结束标签?像这样:
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'));
推荐答案
虽然如果你不使用结束标签(或者至少自己关闭标签)可能会起作用,你应该添加一个结束标签(self-close)(如上所述,为了跨平台兼容性):
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):
为确保跨平台兼容性,代码段必须格式正确.可以包含其他元素的标签应与结束标签配对:
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>');
另外,jQuery 允许类似 XML 的标记语法(斜杠前有或没有空格):
Alternatively, jQuery allows XML-like tag syntax (with or without a space before the slash):
$('<a/>');
不能包含元素的标签可以快速关闭也可以不:
Tags that cannot contain elements may be quick-closed or not:
$('<img />');
$('<input>');
这是 jQuery 创建元素的方式:
This is how jQuery creates the elements:
如果 HTML 比没有属性的单个标记更复杂,如上例所示,则元素的实际创建由浏览器的 innerHTML
机制处理.在大多数情况下,jQuery 会创建一个新元素并将该元素的 innerHTML
属性设置为传入的 HTML 片段.当参数具有单个标记时,例如 $('<img/>')
或 $('<a></a>')
,jQuery 使用原生 JavaScript createElement()
创建元素代码>函数.
If the HTML is more complex than a single tag without attributes, as it is in the above example, the actual creation of the elements is handled by the browser's
innerHTML
mechanism. In most cases, jQuery creates a new element and sets theinnerHTML
property of the element to the HTML snippet that was passed in. When the parameter has a single tag, such as$('<img />')
or$('<a></a>')
, jQuery creates the element using the native JavaScriptcreateElement()
function.
<小时>
顺便说一句.您也可以将数据作为第二个参数传递:
Btw. you can also pass the data as second parameter:
$('<div />', {'class': 'error', text: 'Error-Homie!'})
这篇关于jQuery:创建新元素时,是否需要结束标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!