jQuery:创建新元素时,是否需要结束标记? [英] jQuery: When creating a new element, do I need the ending tag?

查看:24
本文介绍了jQuery:创建新元素时,是否需要结束标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var $div = $('<div class="error">').appendTo($('#header'));

在创建新元素并将它们添加到 DOM 时,是否需要结束标记?为什么或者为什么不?如果我将内容放入我创建的标签中,我是否只需要结束标签?像这样:

var $div = $('

Error-Homie! </div>').appendTo($('#header'));

或者我可以创建一个包含内容的元素,但省略结束标签吗?好的?不好?

var $div = $('<div class="error">').appendTo($('#header'));

解决方案

虽然如果你不使用结束标签(或者至少自己关闭标签)它可能会工作,你应该添加一个结束标签(self-close)(如前所述,为了跨平台兼容性):

<块引用>

为确保跨平台兼容性,代码段必须格式正确.可以包含其他元素的标签应该与结束标签配对:

$('<a href="http://jquery.com"></a>');

或者,jQuery 允许类似 XML 的标记语法(斜线前有或没有空格):

$('');

不能包含元素的标签可能会被快速关闭:

$('');$('<输入>');

这就是 jQuery 创建元素的方式:

<块引用>

如果 HTML 比没有属性的单个标签更复杂,如上例所示,元素的实际创建由浏览器的 innerHTML 机制处理.大多数情况下,jQuery 会创建一个新元素,并将该元素的 innerHTML 属性设置为传入的 HTML 片段.当参数具有单个标记时,例如 $('<img/>')$('<a></a>'),jQuery 使用原生 JavaScript 创建元素 createElement()代码>函数.

<小时>

顺便说一句.您还可以将数据作为第二个参数传递:

$('

', {'class': 'error', text: 'Error-Homie!'})

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

解决方案

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!'})

这篇关于jQuery:创建新元素时,是否需要结束标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆