在’each’函数中使用jQuery查询JSON数据

我是JSON的新手,我正试图找到一种方法来查询JSON数据并将信息带到我页面上的相应

。 我正在使用Volusion,因此对代码的访问是有限的(它主要是从服务器端脚本动态生成的)所以我不得不做几个解决方法。 基本上有一个产品表,获取产品代码的唯一方法是从这些产品的锚标签上生成的URL中获取它(每个产品都设置有附加到的链接,例如/ ProductDetails.asp?ProductCode =香气产品的香气)。 我编写了Javascript来提取产品代码(从URL的末尾)并将其设置为名为productCode的变量。

在我的JSON数据中,我设置如下:

 [ { "item": "aroma", "title": "Aromatherapy Oils", "price": "$10.00", }, { "item": "ah-chairbamboo", "title": "Modern Bamboo Chair", "price": "$100.00", }, { "item": "hc-mirror", "title": "Cordless LED Lighting Pivoting Vanity Mirror", "price": "$45.00", }, { "item": "macfrc", "title": "French Macarons", "price": "$15.00", } ] 

如果我想从JSON表中获取标题,其中’aroma’是项目并将其附加到div中的产品容器中,该怎么办? 我的代码现在获取产品代码的方式是:

 $(".v65-productDisplay a").each(function(){ var productHref = $(this).attr("href"); var productCode = productHref.substring(19,productHref.length); 

这是有效的,因为我已经提醒了productCodes并且它们都是正确的。

我希望这个JSON查询显然在每个函数中,因此它在页面上的每个产品上运行。 在英语中,我想说“项目值与JSON表中的产品代码匹配,我想打印出那个标题和价格”(是的,我明白这不是很好的英语……)。

我第一次尝试查询它(并警告其价值)的失败尝试就在这里。 这是在:

 $(".v65-productDisplay a").each(function(){ var productHref = $(this).attr("href"); var productCode = productHref.substring(19,productHref.length); $.getJSON("/v/vspfiles/data/productinfo.js", function (data) { $.each(data, function () { if (productCode = this['item']) alert(this['price']); }); }); 

});

但这没用。 对不起,如果这令人困惑,我正试图自己解决它。 非常感谢您的帮助。


编辑

这是一个新的更新片段,继PSCoder的答案之后,仍然没有完全正常工作:

 $.getJSON("/v/vspfiles/data/productinfo.js", function (data) { $.each(data, function (i,o) { if (productCode == o.item) alert(o.price); }); }); 

你可以这样做:

 $.getJSON("/v/vspfiles/data/productinfo.js", function (data) { $.each(data, function () { if (productCode.trim() === this.item) console.log(this['price']); }); });