我尝试基于jquery和json文件创建一个简单的搜索,我想在搜索特定的tag
之后获得具有相同Title
的数据,这里是json
[
{
"title": " Title one ",
"description": " description one ",
"link": "http://expample1.com",
"tag": {
"tag1": "Stackoverflow",
"tag2": "Demo one"
}
},
{
"title": " Title Two ",
"description": " description Two ",
"link": "http://expample2.com",
"tag": {
"tag1": "Stackoverflow",
"tag2": "Demo two"
}
},
{
"title": " Title Three ",
"description": " description Three ",
"link": "http://expample3.com",
"tag": {
"tag1": "Tag thre",
"tag2": "Demo Three"
}
}
]
这是JSFIDDLE
上的DEMO例如,当我输入标题一时,我想显示标题一和标题二,因为它们具有相同的tag1: stackoverflow
答案 0 :(得分:0)
你可以这样尝试
html代码
<div class="ui-widget">
<input type="text" name="search" id="search">
<div id="res"></div>
</div>
javascript代码
$(document).ready(function(){
$('#search').bind("enterKey",function(e){
var want = $("#search").val();
var myExp = new RegExp(want, "i");
var data = [
{
"titre": " Title one ",
"description": " description one ",
"link": "http://expample1.com",
"tag": {
"tag1": "Stackoverflow",
"tag2": "Demo one"
}
},
{
"titre": " Title Two ",
"description": " description Two ",
"link": "http://expample2.com",
"tag": {
"tag1": "Stackoverflow",
"tag2": "Demo two"
}
},
{
"titre": " Title Three ",
"description": " description Three ",
"link": "http://expample3.com",
"tag": {
"tag1": "Tag thre",
"tag2": "Demo Three"
}
}
];
var output = '<ul class="results">';
var bool = false;
$.each(data, function(key, val){
for(var prop in val) {
console.log(prop);
console.log(typeof val[prop]);
if(typeof val[prop] == 'object') {
output += checkNestedTag(want, val[prop]);
}
if(prop == want && typeof val[want] != 'object') {
output += '<li>';
output += '<h3>'+ val[want]+'</a></h3>';
output += '</li>';
} else if(typeof val[want] == 'object')
bool = true;
}
});
if(bool)
output += '<li>Value is in object</li>';
output += '</ul>';
$("#res").html(output);
});
$('#search').keyup(function(e){
if(e.keyCode == 13){
$(this).trigger("enterKey");
}
});
});
function checkNestedTag(want, val) {
var output = '';
for(var prop in val) {
if(typeof val[prop] == 'object') {
output += checkNestedTag(want, val[prop]);
}
if(prop == want) {
output += '<li>';
output += '<h3>'+ val[want]+'</a></h3>';
output += '</li>';
}
}
return output;
}
我不确定,但我认为这对你很有帮助。 http://jsfiddle.net/szvvh8dL/1/
答案 1 :(得分:-1)
在这里,您可以进行基本搜索。现在你只需要再次循环并检查相同的标签。
http://jsfiddle.net/8xhnyueo/3/
我的搜索算法是:
$('#search').on("keyup", function() {
$("#res").empty();
for(var i=0;i<data.length;i++){
if(data[i].titre.indexOf($(this).val()) !== -1) {
var output = '<li>';
output += '<h3><a href='+ data[i].link +' target="blank">'+ data[i].titre + '</a></h3>';
output += '<span>'+ data[i].description +'</span>';
output += '<h6>'+ data[i].tag.tag1 +''+ data[i].tag.tag2 +'</h6>';
output += '<h6></h6>';
output += '</li>';
$("#res").append(output);
}
}
});