我创建了这段代码来搜索我的JSON数据,但我还没有找到它为什么不起作用的线索。有人可以分析一下吗?
我基本上需要一个HTML搜索框来搜索相应的JSON数据并将其返回。
<script>
$('#txt-search').keyup(function(){
var searchField;
$.getJSON('example.json', function(data) {
searchField = data.val();
});
if(searchField === '') {
$('#filter-records').html('');
return;
}
var regex = new RegExp(searchField, "i");
var output = '<div class="row">';
var count = 1;
$.each(data, function(key, val){
if ((val.employee_salary.search(regex) != -1) || (val.employee_name.search(regex) != -1)) {
output += '<div class="col-md-6 well">';
output += '<div class="col-md-3"><img class="img-responsive" src="'+val.profile_image+'" alt="'+ val.employee_name +'" /></div>';
output += '<div class="col-md-7">';
output += '<h5>' + val.employee_name + '</h5>';
output += '<p>' + val.employee_salary + '</p>'
output += '</div>';
output += '</div>';
if(count%2 == 0){
output += '</div><div class="row">'
}
count++;
}
});
output += '</div>';
$('#filter-records').html(output);
});
</script>
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Request JSON Test</title>
</head>
<body>
<div class="container" style="padding:50px 250px;">
<form role="form">
<div class="form-group">
<input type="input" class="form-control input-lg" id="txt-search" placeholder="Type your search character">
</div>
</form>
<div id="filter-records"></div>
</div>
</body>
</html>
&#13;
答案 0 :(得分:0)
您需要在正则表达式函数中解析参数。这是我建立的一个例子,你可以得到一个想法:
var data = [
{
"id":198,
"name":"Aaron Garo",
},
{
"id":345,
"name":"Michael Stines",
},
{
"id":545,
"name":"Ully Heiz",
},
{
"id":678,
"name":"Asgaf Torino",
}
]
output = "";
$.each(data, function(key, val){
output += "<div class='values'>";
output += '<h5 class="value-id">' + val.id + '</h5>';
output += '<p class="value-name">' + val.name + '</p>'
output += "</div>";
});
$('#content').html(output);
/* SEEKER FUNCTION */
if (!RegExp.escape) {
RegExp.escape = function (s) {
return s.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
};
}
jQuery(function(){
var $rows = $('.values');
$('#seeker').keyup(function () {
var regex = new RegExp(RegExp.escape($.trim(this.value).replace(/\s+/g, ' ')), 'i')
$rows.hide().filter(function () {
var text = $(this).children(".value-name").text().replace(/\s+/g, ' ');
return regex.test(text)
}).show();
});
});
&#13;
.values{
background: #FFFFAA;
}
.search-bar input{
width: 100%;
}
&#13;
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<div class="search-bar">
<input type="text" id="seeker">
</div>
<div id="content"></div>
&#13;