您好我想知道是否可以在给定属性中对json数据应用部分搜索。我想做的是,如果我输入我的意见,说" Jac"然后它会搜索我的json数据,找到像Jacob,Jack,Jacqueline等类似的字符串。这是我的代码:
var data = [{
"RM_Name": "Russ Martin",
"Division": "East",
"RM_Phone": "(603) 491-1259",
"RC_Name": "Jacob Sucoff",
"RC_Phone": "(800) 247-4154 x3403",
"States_Covered": "MT,VT, NH, ME (all firms)",
"Latitude": 46.6797995,
"Longitude": -110.044783,
"Coordinates": "46.6797995,-110.044783"
}, {
"RM_Name": "Carey Fortnam",
"Division": "East",
"RM_Phone": "(585)-259-7394",
"RC_Name": "Matt Wrzesniewsky",
"RC_Phone": "(800) 247-4154 x3088",
"States_Covered": "NY- Upstate ex Rockland County (BD, FP)",
"Latitude": 40.7056308,
"Longitude": -73.9780035,
"Coordinates": "40.7056308,-73.9780035"
}];
$.each(data, function(i, item) {
var rm_name = item.RM_Name,division = item.Division,rm_phone = item.RM_Phone,rc_name = item.RC_Name,rc_phone = item.RC_Phone,states = item.States_Covered;
var dataset='<tr class="'+rm_name+' '+rc_name+'"><td>'+rm_name+'</td><td>'+division+'</td><td>'+rm_phone+'</td><td>'+rc_name+'</td><td>'+rc_phone+'</td><td>'+states+'</td></tr>';
$('.rm-data').append(dataset);
});
$('#search').on('keypress', function (e) {
if(e.which == 13){
var query = $('#search').val();
$('.rm-data tr').hide();
$('.error-msg').hide();
if ($('.rm-data tr').hasClass(query)) {
$('.rm-data tr:contains(' + query + ')').fadeIn('slow', function () {
$('.rm-data tr:contains(' + query + ')').slideDown().show();
});
}
else {
var error = '<div class="error-msg">Contact Not Found</div>';
$('.rm-table-search').append(error);
if ($('.error-msg').length == 0) {
$('.rm-table').append(error);
}
else {
$('.rm-table').append('');
}
}
}
});
以及指向我Fiddle
的链接答案 0 :(得分:1)
我会做这样的事情:
我做了什么:
change
事件添加到搜索输入事先键入的内容:
var typeaheadData = []; // initializer
typeaheadData.push(rm_name); // in your each loop
$('#search').typeahead({ // append source to typeahead plugin
source: typeaheadData });
空搜索
if(query === "")
{
$('.rm-data tr').show();
return;
}
事件
.on('change', function (e) {
search();
});
我还将搜索部分提取到search
方法中,以便我们可以从代码中的其他点调用