我不断收到未捕获的类型错误:无法读取未定义的属性“搜索”
$('.searchBar').keydown(function(){
$.getJSON('js/data.json', function(data){
var search = $('.searchBar').val();
var regex = new RegExp(search, 'i');
$.each(data, function(key,val){
if((val.id.search(regex) != -1) || (val.title.search(regex) != -1)){
var img = "<img src= " + val.imgUrl + "/>"
var title = "<h1>" + val.title + "</h1>";
var description = "<p>" + val.description + "</p>";
var cta = "<button><a href= " + val.ctaUrl + ">" + "</a>Find out more about this product</button>";
$(img).appendTo('#data');
$(title).appendTo('#data');
$(description).appendTo('#data');
$(cta).appendTo('#data');
}
});
});
})
更新 - 这是我的 JSON 文件(其中一些):
"results": [
{
"id": "56c1b27e896f0e4141b775b6",
"title": "Product 1",
"ctaUrl": "/product-1",
"imgUrl": "http://placehold.it/275x155",
"description": "Anim mollit cupidatat duis est adipisicing veniam.Proident culpa voluptate labore consectetur nulla cupidatat eu aliquip ad cillum consequat quis aliquip."
}
最佳答案
添加检查 val
是否包含 id
和/或 title
,如下所示:
var textAndId = '';
textAndId += ('id' in val) ? val.id : '';
textAndId += ('title' in val) ? val.title : '';
并以这种方式添加到您的代码中:
$.each(data, function(key,val){
var textAndId = '';
textAndId += ('id' in val) ? val.id : '';
textAndId += ('title' in val) ? val.title : '';
if(textAndId.search(regex) != -1){
关于javascript - 使用 Jquery 搜索 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39248130/