计算给定输入的出现次数

如果我有一个带有简单提交按钮的输入框,有没有办法跟踪在给出某些输入时单击按钮的次数。 例如,我输入牛奶并点击提交,牛奶计数将为1,再次点击牛奶计数将是两个。 我知道使用一个简单的计数器变量,我可以跟踪计数,但计数本身与任何特定输入都不匹配,它只是按钮点击的通用计数器。 我可以将输入中的值存储在数组中,然后计算特定项的出现次数以查找其计数,但有更优雅的方法吗?

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

初始化一个Array var listCount = []; ,将输入值存储为关联键,并将parseInt(initVal)+1增加n次单击的值。

您可以使用简单object来存储事件。 基本思想是获取输入值并将其添加到对象,使用输入作为索引,其值为添加的次数。

 $(document).ready(function(){ // Create simple storage var items = {}; $('#submit').click(function(event){ event.preventDefault(); var item = $('#item').val(); items[item] = items[item]+1 || 1; $('#result').html(JSON.stringify(items)); $('#item').val(''); }); }); 
    

没有jQuery的解决方案,以及一些格式良好的JSON:

 // Create storage and find nodes we need var items = {}; var btn = document.getElementById('submit'); var textInput = document.getElementById('item'); var result = document.getElementById('result'); // Add event-handler for button click btn.addEventListener('click', function(event){ event.preventDefault(); // Increment counter items[textInput.value] = items[textInput.value]+1 || 1; // Prettyprint the result result.textContent = JSON.stringify(items, null, 2); // Reset text textInput.value = ''; });