我的.json位于https://aaronlilly.github.io/PokeApp/api/v2/pokemon/FakeLego2.json
{
"results":
[
{
"ID": 2924,
"SetNumber": 7942,
"URL": "https://www.lego.com/biassets/bi/4586972.pdf",
"Images": "https://www.lego.com/biassets/biimg/4586972.png",
"Description": "Off Road Fire Rescue",
"DashedNumber": "7942-1",
"Preselect": "fire"
},
{
"ID": 4470,
"SetNumber": 7942,
"URL": "https://www.lego.com/biassets/bi/4656089.pdf",
"Images": "https://www.lego.com/biassets/biimg/4656089.png",
"Description": "Police Boat",
"DashedNumber": "7287-1 ",
"Preselect": "police"
}
],"next":"1
我的脚本是
$(document).ready(function () {
$('#search-now').click(function () {
$.ajax
({
method: "GET",
url: "https://aaronlilly.github.io/PokeApp/api/v2/pokemon/FakeLego2.json"
}).done(function (data) {
for (var i = 0; i < data.results.length; i++) {
$("#legoList").append(data.results[i].Preselect + "<br>");
}
});
});
});
我希望我的示例很简单,所以我创建了这个.json文件,但最后,我想让用户在字段中键入搜索并返回与包含搜索中单词的描述相匹配的项目字段。
更新
我找到了如何过滤的方法,但我仍在努力进行动态过滤。在下面,我创建一个名为obj的数组,并将其设置为与json一样,然后将ID为2924的项过滤器写入控制台。
var obj = {
'results': [{
"ID": 2924,
"SetNumber": 7942,
"URL": "https://www.lego.com/biassets/bi/4586972.pdf",
"Images": "https://www.lego.com/biassets/biimg/4586972.png",
"Description": "Off Road Fire Rescue",
"DashedNumber": "7942-1",
"Preselect": "fire"
}, {
"ID": 4470,
"SetNumber": 7942,
"URL": "https://www.lego.com/biassets/bi/4656089.pdf",
"Images": "https://www.lego.com/biassets/biimg/4656089.png",
"Description": "Police Boat",
"DashedNumber": "7287-1 ",
"Preselect": "police"
},
]
};
var newArray = obj.results.filter(function (el) {
return el.ID == 2924 &&
el.SetNumber &&
el.URL &&
el.Images &&
el.Description &&
el.DashedNumber &&
el.Preselect ;
});
console.log(newArray);
我现在想动态地执行此操作。
我已在页面上添加了一个字段
<input type="text" id="prodId" size="37" placeholder="Search Field" style="margin-left: 50px;margin-top: 10px;padding-bottom: 5px;padding-top: 4px;">
所以我尝试将prodId值移到我的新数组中,但这不太起作用。
var newArray = obj.results.filter(function (el) {
return el.ID == $('#prodId').val() &&
el.SetNumber &&
el.URL &&
el.Images &&
el.Description &&
el.DashedNumber &&
el.Preselect ;
});
console.log(newArray);
希望您看到我正在尝试:)任何建议都很好。
答案 0 :(得分:0)
这是方法。
$(document).ready(function (){
$('#prodId').click(function () {
var newArray = obj.results.filter(function (el) {
return el.ID == $('#prodId').val() &&
el.SetNumber &&
el.URL &&
el.Images &&
el.Description &&
el.DashedNumber &&
el.Preselect ;
});
console.log(newArray);
这将显示与(ID,即2924或4470)的完全匹配