我正在尝试使用 jQuery 替换背景图像。
图像是从 API 调用的,下面是 JSON 数据的 fiddle 。
https://jsfiddle.net/m15xg45j/
这个 JS Fiddle 包含所有 HTML、CSS 和 JS 的完整代码
https://jsfiddle.net/bsu6m5es/2/
我的JS
var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
url += '?' + $.param({
'api-key' : "***",
'q' : "health"
});
$.ajax({
url: url,
method: 'GET',
}).done(function(result){
var articles = result.response.docs;
for(var i=0; i<articles.length; i++){
$("h2").each(function(index, el){
$(el).html(articles[index].headline.main);
});
$(".article--snippet").each(function(index, el){
$(el).html(articles[index].snippet);
});
$(".post").each(function(index, el){
$("el").css("background", "url(" + articles[index].thumbnail +")");
});
// console.log(articles[i].url);
$(".linked--headline").each(function(index, el){
$(el).attr("href", articles[index].web_url);
});
// console.log(articles[i].web_url);
}
}).fail(function(err){
throw err;
});
最佳答案
运行成功方法,而不是使用“完成”方法:
根据您提供的数据结构,您需要运行 for 循环并对多媒体属性使用过滤器。检查代码
https://jsfiddle.net/bsu6m5es/3/
var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
url += '?' + $.param({
'api-key' : "67dac4e994164fca920f7a8420e28dc2",
'q' : "health"
});
$.ajax({
url: url,
method: 'GET',
success : function(result){
var articles = result.response.docs;
for(var i=0; i<articles.length; i++){
$("h2").each(function(index, el){
$(el).html(articles[index].headline.main);
});
$(".article--snippet").each(function(index, el){
$(el).html(articles[index].snippet);
});
$(".post").each(function(index, el){
$("el").css("background", "url(" + articles[index].thumbnail +")");
});
// console.log(articles[i].url);
$(".linked--headline").each(function(index, el){
$(el).attr("href", articles[index].web_url);
});
/// Your thumbnails:
for (var i=0;i<r.response.docs.length;i++)
{
var thumbUrl = r.response.docs[i].multimedia.filter(function(el){ return el.subtype='thumbnail'})[0].url;
// e.g: thumbUrl = 'images/2017/02/28/science/28BRODY/28BRODY-thumbWide.jpg'
}
// console.log(articles[i].web_url);
}
}).fail(function(err){
throw err;
});
关于javascript - 使用 jQuery 从 API 显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42493704/