计算给定输入的出现 [英] Counting occurrences of a given input
问题描述
如果我有一个带有简单提交按钮的输入框,是否可以跟踪给出特定输入时单击按钮的次数.例如,我输入牛奶并点击提交,牛奶计数将为1,再次单击牛奶计数将为2.我知道使用一个简单的计数器变量,我可以跟踪计数,但是计数本身不匹配任何特定的输入,它只是按钮单击的通用计数器.我可以将输入中的值存储在数组中,然后对特定项目的出现进行计数以找到其计数,但是有没有更优雅的方法呢?
If I had an input box with a simple submit button, is there a way to keep track of the amount of times the button was clicked when certain input was given. For instance, I enter milk and hit submit, milk count would be 1, click again milk count would be two. I know that using a simple counter variable, I can keep track of the count, but the count would not match any particular input per se, it's just a generic counter of button clicks. I could store the values from the input in an array and then count the occurrences of a particular item to find its count, but is there a more elegant way to do this?
推荐答案
var listCount = [];
$("#getButton").click(function() {
var getTextValue = $("#getInput").val();
if(getTextValue!="") {
var initVal = typeof(listCount[getTextValue])=="undefined" ? 0 : listCount[getTextValue];
listCount[getTextValue] = parseInt(initVal)+1;
alert(listCount[getTextValue]);
}
return false;
});
初始化一个数组var listCount = [];
,该数组将输入值存储为关联键,并且parseInt(initVal)+1
将值增加n次单击.
Initialized an Array var listCount = [];
, which stores the Input Value as Associative Key, and parseInt(initVal)+1
increments the value of n times click.
这篇关于计算给定输入的出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!