我有这样的代码:

<div id="header">
    <ul class="tabs">
        <li><a href="/user/view"><span class="tab">Profile</span></a></li>
        <li><a href="/user/edit"><span class="tab">Edit</span></a></li>
    </ul>
</div>

我想使用jQuery添加以下到列表:

<li><a href="/user/messages"><span class="tab">Message Center</span></a></li>

我试了一下:

$("#content ul li:last").append("<li><a href="/user/messages"><span class="tab">Message Center</span></a></li>");

但是这会在最后一个li中(就在结束标记之前)添加新的li,而不是在最后一个li之后。加上这个li的最好方法是什么?


当前回答

使用jquery的prepend()函数在ul中添加li作为第一项

$("ul").prepend("<li>first item</li>");

使用jquery的append()函数在ul中添加li作为最后一项

$("ul").append("<li>last item</li>");

其他回答

而不是

$("#header ul li:last")

try

$("#header ul")
$("#content ul").append('<li><a href="/user/messages"><span class="tab">Message Center</span></a></li>');

Use:

// Creating and adding an element to the page at the same time.
$("ul").append("<li>list item</li>");

这是另一个

$("#header ul li").last().html('<li> Menu 5 </li>');

这是你能做到的最短的方法:

list.push($('<li>', {text: blocks[i] }));
$('ul').append(list);

其中blocks是一个数组。你需要对数组进行循环。