简体   繁体   English

在页面加载和每次单击某些按钮时运行jQuery函数

[英]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: 我有一个带有多个列表项的ul ,并且正在使用jQuery来:

  1. Count the number of list items 计算列表项的数量
  2. Output that value to a different div 将该值输出到另一个div
  3. Change the color of the output text if that value is greater than 13 如果该值大于13,则更改输出文本的颜色

In a different div, I have multiple buttons with the class .add or .delete . 在不同的div中,我有多个带有.add.delete类的按钮。 Not surprisingly, clicking these buttons adds or deletes list items. 毫不奇怪,单击这些按钮可以添加或删除列表项。

The jQuery function works perfectly when the page is loaded, but what I'd like to also do is have this count update every time one of the above buttons is clicked. 当页面加载时,jQuery函数完美运行,但是我还想做的是每次单击以上按钮之一时更新此计数。

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. 抱歉,如果我缺少什么,但基本上是:将代码包装在一个函数中,在页面加载时调用该函数,并在处理完按钮单击后调用该函数。

Eg: 例如:

// 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());
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM