问题描述
在以下JSON数据中,A项目的防过敏字符串中包含麸质",而B项目则没有.我可以在A项目中添加<h4>Yes</h4>
,但我也想在B项目中添加<h4>No</h4>
,因为它在字符串中不包含面筋".其他无过敏值也是如此.
In the following JSON data, A item has "gluten" in the allergyfree string while B item doesn't. I can add a <h4>Yes</h4>
to A item but I also want to add a <h4>No</h4>
to B item since it doesn't contain "gluten" in the string. The same goes for the other allergyfree values.
是否可以在循环中比较A项目和B项目之间的防过敏字符串,以便如果该项目具有值(例如面筋),则打印<h4>Yes</h4>
,如果缺少,则打印<h4>No</h4>
?
Is there any way to compare the allergyfree strings between A item and B item in the loop, so that if the item has the value, for example, gluten, then print <h4>Yes</h4>
, if missing, print <h4>No</h4>
?
[{"title":"A Item","allergyfree":"sugar,salt,yeast,wheat,gluten"},{"title":"B Item","allergyfree":"sugar,salt,starch,yeast,wheat,preservatives"}]
代码:
$.ajax({
url: source.json,
success: function (data) {
var item_html;
$(data).each(function (index, item) {
var allergyfree = item.allergyfree;
if(allergyfree.length !== 0) {
allergyfree = allergyfree.split(",");
$.each(allergyfree,function(i,allergy){
if (?????????????????)
{
$('.'+ allergy).html('<h4>Yes</h4>')
}
else
{
$('.'+ allergy).html('<h4>No</h4>')
}
});
}
});
},
error: function () {}
});
HTML
<table>
<tr><th colspan="3">A Item</th></tr>
<tr><td class="gluten"></td>
<td class="sugar"></td>
<td class="yeast"></td></tr>
</table>
<table>
<tr><th colspan="3">B Item</th></tr>
<tr><td class="gluten"></td>
<td class="sugar"></td>
<td class="yeast"></td></tr>
</table>
推荐答案
您可以使用 $ .inArray函数返回项目在数组中的位置,如果不存在则返回-1:
You could use $.inArray function it returns position of item in array and -1 if item is not present :
if ($.inArray(alergy,allergyfree)!=-1)
这篇关于比较价目表,找到失踪者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!