gpt4 book ai didi

jQuery:创建新元素时,我需要结束标签吗?

转载 作者:行者123 更新时间:2023-12-03 22:14:46 25 4
gpt4 key购买 nike

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

最佳答案

尽管如果您不使用结束标签(或至少自行关闭标签),它可能会起作用,you should add a closing tag (self-close) (如上所述,为了跨平台兼容性):

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

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

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.

<小时/>

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

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

关于jQuery:创建新元素时,我需要结束标签吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6555898/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com