jQuery: When creating a new element, do I need the ending tag?

戏子无情 提交于 2019-11-29 17:40:08

问题


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

回答1:


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

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

This is how jQuery creates the elements:

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 the innerHTML 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 JavaScript createElement() function.


Btw. you can also pass the data as second parameter:

$('<div />', {'class': 'error', text: 'Error-Homie!'})



回答2:


you need the ending tag : http://api.jquery.com/appendTo/ for example

$('<p>Test</p>').appendTo('.inner');

it should also be

.appendTo('#header');

and not

.appendTo($('#header'));



回答3:


you can probably do it like this

$('<div/>',{class:'error'}).html('Error-Homie!').appendTo($('#header'));



回答4:


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.



来源:https://stackoverflow.com/questions/6555898/jquery-when-creating-a-new-element-do-i-need-the-ending-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!