我建议您创建一个函数,并验证是否未定义附件。以下是完整的示例:
<html>
<head>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function getRSSFeed(feed){
// Build the YQL query
var qryRSS = 'select * from rss where url='+'"'+feed+'"';
// Initiate the YQL query
$.getJSON("http://query.yahooapis.com/v1/public/yql",
{
// settings API call
q: qryRSS,
format: "json"
},
function(data) {
for (i=0; i<4; i++)
{
// Output a link, using the link attribute and the title attribute
$('body').append('<a href="'+data.query.results.item[i].link+'">'+data.query.results.item[i].title+mountImg(data.query.results.item[i].enclosure)+'</a>');
// Output the description, using the description attribute.
$('body').append(data.query.results.item[i].description);
}
});
};
function mountImg(enclosure){
if(typeof enclosure !== 'undefined')
return '<img src="'+enclosure.resource+'" />';
}
getRSSFeed('https://swmi.craigslist.org/search/sss?format=rss&query=grand%20prix');
</script>
</body>
</html>