Javascript 在页面加载和每次单击某些按钮时运行 jQuery 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5945368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run jQuery Function on Page Load AND Every Time Certain Buttons Are Clicked
提问by 40 Degree Day
I have a ul
with multiple list items and am using jQuery to:
我有ul
多个列表项,并且正在使用 jQuery 来:
- 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
- 计算列表项的数量
- 将该值输出到不同的 div
- 如果该值大于 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.
在不同的 div 中,我有多个带有 class.add
或.delete
. 毫不奇怪,单击这些按钮会添加或删除列表项。
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!
我需要添加什么才能完成这项工作?我确实查看了这个类似问题的答案(在页面加载时运行一次代码,然后每次单击按钮时),但它们似乎没有帮助。任何帮助将不胜感激!
回答by T.J. Crowder
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();
});
回答by Piotr Kula
//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());
});