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

标签 jquery append element new-operator end-tag

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/

相关文章:

javascript - 我的网页如何在没有点击事件的情况下仅使用 JavaScript 下载服务器上的文件

javascript - jQuery 单击或 touchstart 事件在移动设备上不起作用

javascript - 通过拖动元素传递鼠标悬停事件

c++ - 调试链表指针代码: segmentation fault

jQuery 找到正确的 id

jquery - 通过最后两个字符定位元素

javascript - 如何从父窗口在子窗口中动态创建元素

jQuery .get > 将 div 添加到页面

python - 如何制作具有不同值的相同变量的列表? Python

javascript - 从上面的链接获取文本 - Jquery