Run jQuery Function on Page Load AND Every Time Certain Buttons Are Clicked
I have a ul
with multiple list items and am using jQuery to:
- Count the number of list items
- Output that value to a different div
- Change the color of the output text if that value is greater than 13
In a different div, I have multiple buttons with the class .add
or .delete
. Not surprisingly, clicking these buttons adds or deletes list items.
The jQuery function works perfectly when the page is loaded, but开发者_JS百科 what I'd like to also do is have this count update every time one of the above buttons is clicked.
Here's my existing code:
var totalItems = $('ul#myList li').length;
$('#outputText').text(totalItems);
if (totalItems > 13) {
$('#outputText').css('color','#F0402B');
};
What do I need to add to make this work? I did look at the answers for this similar question (Run code once on page load, then every time a button is clicked) but they didn't seem to help. Any help would be greatly appreciated!
Apologies if I'm missing something, but basically: Just wrap the code up in a function, call that function on page load, and also call the function after processing the clicks on the buttons.
E.g.:
// The function
function updateTotalItems() {
var totalItems = $('ul#myList li').length;
$('#outputText').text(totalItems);
if (totalItems > 13) {
$('#outputText').css('color','#F0402B');
};
}
// Call on page load
$(updateTotalItems);
// Presumably you're setting up click handlers
$(".add, .delete").click(function() {
// Process the add or delete action
// Update the total
updateTotalItems();
});
//Keep this function outside of document ready to avoid anonymous function.
function updateDiv(){
var totalItems = $('ul#myList li').length;
$('#outputText').text(totalItems);
if (totalItems > 13)
{
$('#outputText').css('color','#F0402B');
}
}
$(document).ready(function() {
// do stuff when DOM is ready
updateDiv();
$('.delete').click(updateDiv());
$('.add').click(updateDiv());
});
精彩评论