更新:在if语句中使用return false
只能返回"否"消息。所有"是"消息被跳过。如何才能显示“是”消息?这是更新后的Example。
Example(单个对象循环关键字列表)
Example 2(循环遍历关键字列表的对象数组)
一旦检查到关键字数组存在于返回对象数组中,我就无法获得第二个示例跳转到下一个关键字。当您单击警报消息时,您可以看到“是”消息被“无消息”覆盖,因为它无法转到下一个关键字并继续检查不包含该关键字的其他对象。 / p>
return true;
似乎无法奏效。任何人都可以告诉我如何在返回的对象中找到关键字后跳到下一个循环吗?
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%20%22http%3A%2F%2Fgoo.gl%2FSXYySV%22&format=json&diagnostics=true&callback=",
success: function (data) {
var keywords = ["Germany","England"];
$(data.query.results.json.json).each(function (index, item) {
var nation1 = item.nation1,
nation2 = item.nation2,
title = item.title;
var objects = [nation2,nation1,title];
$.each(objects,function(i,object){
$.each(keywords,function(i,keyword){
alert(keyword)
if ($.inArray(object,keywords)!=-1)
{
$('.'+ title+'_'+keyword).html(title+' contains '+keyword)
return true;
}
else
{
$('.'+ title+'_'+keyword).html(title+' does not have '+keyword)
}
});
});
});
}
});
HTML:
<div class="A_Germany"></div>
<div class="B_Germany"></div>
<div class="C_Germany"></div>
<div class="A_England"></div>
<div class="B_England"></div>
<div class="C_England"></div>
JSON
[{"title":"A","nation1":"Turkey","nation2":"Germany"},{"title":"B","nation1":"France","nation2":"Japan"},{"title":"C","nation1":"Italy","nation2":"England"}]
预期输出应为
<div class="A_Germany">Yes</div>
<div class="B_Germany">No</div>
<div class="C_Germany">No</div>
<div class="A_England">No</div>
<div class="B_England">No</div>
<div class="C_England">Yes</div>
答案 0 :(得分:2)
好的,原谅我重命名你的变量 - 我不得不给他们上下文。
不是针对所有项目循环每个团队,而是针对每个团队检查每个特定项目一次,例如A_England
仅检查A and England
而非A but not England
var teams = ["Germany","England"];
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%20%22http%3A%2F%2Fgoo.gl%2FSXYySV%22&format=json&diagnostics=true&callback=",
success: function (data) {
$(data.query.results.json.json).each(function (index, item) {
// make an array of the nations
var arr = [item.nation1, item.nation2];
// check for a team in this game
$.each(teams, function(i, team){
team_index = $.inArray(team, arr);
if (team_index > -1){
$('.'+ item.title + '_'+ team).html("Yes");
}else{
$('.'+ item.title + '_'+ team).html("No");
}
});
});
}
});
我还检查过,当你添加更多团队时它会起作用。 http://jsfiddle.net/9mwCG/28/