当我在搜索栏中输入名称后,从json文件中获取结果时,我试图在我的jquery搜索中使用count来查找找到的匹配项总数。目前,我只在每个结果后显示1个匹配项,而不是搜索中匹配的总数。我在这里缺少什么吗?谢谢
这是代码
$(document).ready(function() {
$('#search').keyup(function() {
$('#result').html('');
var searchField = $('#search').val();
var expression = new RegExp(searchField, "i");
$.getJSON('address.json', function(data) {
$.each(data, function(key, value) {
var count = 0;
if (value.name.search(expression) != -1) {
count++;
$('#result').append('<li class="list-group-item">'
+ value.name + '</li>');
$('#result').append(count + 'Matches Shown');
}
if (searchField == "") {
$('#result').html(""); // this clears the SearchBar
return; // this makes the bar return to it's original state
}
});
});
});
});
答案 0 :(得分:1)
您将在每次迭代中重置count
。在每个函数之外定义它。
$(document).ready(function() {
$('#search').keyup(function() {
$('#result').html('');
var searchField = $('#search').val();
var expression = new RegExp(searchField, "i");
var count = 0;
$.getJSON('address.json', function(data) {
$.each(data, function(key, value) {
if (value.name.search(expression) != -1) {
count++;
...