I have a span which contains the number of a element(in this case it counts the number of li elements in a list), these list items can be deleted so the number will change, how can i live update the number everytime the list gets changed?
This is the code that i use to count the list items
var getTotal = jQuery('#ul li').length;
$(".gettotal开发者_如何学运维").text(getTotal);
I have looked on google but i didn't find anything.
How are your li elements created or deleted? You'll want to trigger a count update on that event. You can utilize jQuery's ability to create/trigger custom events with bind and trigger.
$('#ul').bind('li_deleted', function()
{
$('.gettotal').text( $('#ul li').length );
});
//and every time an li is deleted..
$('#ul').trigger('li_deleted');
Another (and not so good) option is to run a timer on the page, and check if the # of list elements changes - but that's going to be very resource intensive, i wouldn't do it unless it was a last resort.
Depending on how often your list length changes, you may want to have a look at the Data-Link plugin for jQuery.
http://api.jquery.com/category/plugins/data-link
精彩评论