How to add
  • in an existing
      ?
  • 2019-01-02 16:40发布

    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:

    <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. What's the best way to add this li?

    12条回答
    刘海飞了
    2楼-- · 2019-01-02 16:53

    If you are simply adding text in that li, you can use:

     $("#ul").append($("<li>").text("Some Text."));
    
    查看更多
    伤终究还是伤i
    3楼-- · 2019-01-02 16:56

    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.
    • You need to use the opposite type of quotes than what you're using in your HTML. So since you're using double quotes in your attributes, surround the code with single quotes.
    查看更多
    倾城一夜雪
    4楼-- · 2019-01-02 16:56

    Instead of

    $("#header ul li:last")
    

    try

    $("#header ul")
    
    查看更多
    梦寄多情
    5楼-- · 2019-01-02 16:57
    $("#content ul").append('<li><a href="/user/messages"><span class="tab">Message Center</span></a></li>');
    
    查看更多
    长期被迫恋爱
    6楼-- · 2019-01-02 16:58

    This is the shortest way you can do that

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

    Where blocks in an array. and you need to loop through the array.

    查看更多
    皆成旧梦
    7楼-- · 2019-01-02 17:03
    $("#content ul").append('<li><a href="/user/messages"><span class="tab">Message Center</span></a></li>');
    

    Here is some feedback regarding Code Readability (shameless plug for a blog). http://coderob.wordpress.com/2012/02/02/code-readability

    Consider separating the declaration of your new elements from the action of adding them to your UL.. It would look something like this:

    var tabSpan = $('<span/>', {
        html: 'Message Center'
    });
    var messageCenterAnchor = $('<a/>', {
        href='/user/messages',
        html: tabSpan
    });
    var newListItem = $('<li/>', {
        html: messageCenterAnchor,
        "id": "myIDGoesHere"
    });    // NOTE: you have to put quotes around "id" for IE..
    
    $("content ul").append(newListItem);
    

    Happy coding :)

    查看更多
    登录 后发表回答