我如何组装< ul>使用jQuery append()? [英] How do I assemble a <ul> using jQuery append()?

查看:57
本文介绍了我如何组装< ul>使用jQuery append()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用append函数并遇到以下情况:

I'm trying to use the append function and encountered this:

$("#details").append('<ul>');
for (var i = 0; i < 10; i++) {
    $("#details").append('<li>something</li>');
}
$("#details").append('</ul>');

<li>元素似乎呈现在<ul>标签之外.

It appears that the <li> elements renders OUTSIDE the <ul> tag.

这是jQuery的错误吗?

Is this a jQuery bug?

推荐答案

不,这是程序员的错误. <li>附加到其<ul><ol>,而不附加到其容器.并且添加结束标签是没有意义的.

No, it's a programmer bug. <li>s are attached to their <ul> or <ol>, not to its container. And appending a close tag is nonsensical.

您基本上就好像要附加的内容是原始HTML,不是这样.您实际上正在使用DOM.

You're basically working as if what you were appending were raw HTML, and it's not; you're actually working with the DOM.

尝试一下:

var list = $("#details").append('<ul></ul>').find('ul');
for (var i = 0; i < 10; i++)
    list.append('<li>something</li>');

注意:请查看(并赞扬)Blixt的答案,该答案扩展了几个不同的选项,这些选项对于各种目的均是优越的.它值得关注,但一直没有得到它.

Note: please see (and upvote) Blixt's answer, which expands on a couple different options that are superior for various purposes. It deserves attention and hasn't been getting it.

这篇关于我如何组装&lt; ul&gt;使用jQuery append()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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