更新1:
我可以通过try / catch来解决这个问题,但是当我知道问题是什么时,我宁愿不使用这个方法:
try {
buildHTML.push( "<tr><td>" + day.td[0].div.abbr.content + "</td><td><img src='" + day.td[1].div.div.img.src + "' /></td><td>" + day.td[2].span[0].span.content + "</td><td>" + day.td[3].span[0].span.content + "</td><td>" + day.td[4].span[0].span[1].content + "</td>");
} catch(err) {
buildHTML.push( "<tr><td>" + day.td[0].div.abbr.content + "</td><td><img src='" + day.td[1].div.div.img.src + "' /></td><td></td><td>" + day.td[3].span[0].span.content + "</td><td>" + day.td[4].span[0].span[1].content + "</td>");
}
原始问题:
使用以下jsonp服务:
我使用以下脚本来捕获数据:
$(document).ready(function() {
get_bbc_weather();
function get_bbc_weather() {
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%20%3D%20%22http%3A%2F%2Fnews.bbc.co.uk%2Fweather%2Fforecast%2F4276%3F%26search%3Dgerrards%2520cross%26itemsPerPage%3D10%26region%3Dworld%26area%3DGerrards%2520Cross%22%20and%20xpath%3D'%2F%2Ftbody'&format=json&callback=cbfunc22&rand=" + Math.random(),
type: 'GET',
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'cbfunc22',
error: function(xhr, status, error) {
alert(xhr.responseText);
},
success: function(data) {
var buildHTML = [];
var weather = data.query.results.tbody.tr;
buildHTML.push("<tr><td>Day</td><td>Weather</td><td>Max<br />Day<br />(°C)</td><td>Min<br />Night<br />(°C)</td><td>Wind<br />(MPH)</td>");
for (var i = 0; i < weather.length; i++) {
var day = weather[i];
buildHTML.push( "<tr><td>" + day.td[0].div.abbr.content + "</td><td><img src='" + day.td[1].div.div.img.src + "' /></td><td>" + day.td[2].span[0].span.content + "</td><td>" + day.td[3].span[0].span.content + "</td><td>" + day.td[4].span[0].span[1].content + "</td>");
}
$('#divContent1').empty().append("<table>" + buildHTML.join("</tr>") + "</table>")
}
});
}
});
但是,在一天中的某个时间,day.td [2] .span [0] .span.content变为null.发生这种情况时,我如何检测它并使用下一个临时最小部分而不仅仅是第一天?剩下的时间应该继续使用temp max部分.
解决方法:
我可能会在这里说明显而易见的,但为什么不使用if语句呢?
if (day.td[2].span[0].span.content != null) {
buildHTML.push( "<tr><td>" + day.td[0].div.abbr.content + "</td><td><img src='" + day.td[1].div.div.img.src + "' /></td><td>" + day.td[2].span[0].span.content + "</td><td>" + day.td[3].span[0].span.content + "</td><td>" + day.td[4].span[0].span[1].content + "</td>");
}
else {
buildHTML.push( "<tr><td>" + day.td[0].div.abbr.content + "</td><td><img src='" + day.td[1].div.div.img.src + "' /></td><td></td><td>" + day.td[3].span[0].span.content + "</td><td>" + day.td[4].span[0].span[1].content + "</td>");
}