Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

jquery - 如何在现有的<ul>中添加<li>?(How to add <li> in an existing <ul>?)

I have code that looks like this:

(我的代码看起来像这样:)

<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>

I'd like to use jQuery to add the following to the list:

(我想使用jQuery将以下内容添加到列表中:)

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

I tried this:

(我试过这个:)

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

But that adds the new li inside the last li (just before the closing tag), not after it.

(但是,这增加了新li最后 li ,后不是(在结束标记之前)。)

What's the best way to add this li ?

(添加这个li的最佳方法是什么?)

  ask by Eileen translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This would do it:

(这样做:)

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

Two things:

(两件事情:)

  • You can just append the <li> to the <ul> itself.

    (您只需将<li>附加到<ul>本身即可。)

  • You need to use the opposite type of quotes than what you're using in your HTML.

    (您需要使用与您在HTML中使用的相反类型的引号。)

    So since you're using double quotes in your attributes, surround the code with single quotes.

    (因此,由于您在属性中使用双引号,请使用单引号括起代码。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...