0

Basically i'm creating a little to do list app, at the minute I append new list items to a container on button click, this creates the list effect.

What I want to do is add a class to the last element of the list, using last:child works for this but what I need it to do is update the last element when new elements are added, so lets say I have 5 items in a list so the 5th item has class last, when I add a new item I want to remove the class from the old last item and add it to the new last item (that make sense?)

Here's the code I have so far..

<div id="list_container">
    <div id="to_do">
        <ul id="tasks" style="padding:0;">      
        </ul>
    </div>
</div>

var items = [];

// Add new item
$('#add_btn').click(function(event){
    event.preventDefault();

    var list_item = $('#new_item').val();

    // Validation
    if(list_item == ""){
        $('#new_item').addClass('empty');
    }else{ 
        $('#new_item').removeClass('empty').addClass('normal');
        items.push(list_item);
        var lastEl = items[items.length-1];
        $('ul#tasks').append('<li><input type="text" class="to_do_item" value="' + lastEl + '"/></input></li>');
    }

    // Clear input field after adding
    $('#new_item').not(':button, :submit, :reset, :hidden').val('');

});

Anyone know how to achieve this? I'm think it can't be that difficult but I can't seem to think straight right now..

4

2 回答 2

3
...
var lastEl = items[items.length-1];
$('ul#tasks li').removeClass('last');
$('ul#tasks').append('<li class="last"><input type="text" class="to_do_item" value="' + lastEl + '"/></input></li>');
...
于 2013-02-01T21:50:24.027 回答
1
$('.last').removeClass('last')
$('#new_item').addClass('last');

this guarentees nothing has the class 'last', then applies .last to the new li

I would even recommend $(this) instead of $('#new_item')

于 2013-02-01T21:52:32.797 回答