javascript - Change background image dynamically from get response
问题描述
I'm trying to put a background image on div
unsing an image from a get
request.
I'm using jQuery but it doesn't work...
Here is my code:
index.js
<script>
fetch('url').then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
console.log(data['img-detail']); // this is the img
$('.fw .fp-ui').css("background-image", "url(data['img-detail']) !important");
}).catch(function() {
console.log("Error");
});
</script>
<style>
.fw .fp-ui{
background-position: center;
background-size: cover;
}
</style>
解决方案
如果response
是 JSON 对象,您应该重命名img-detail
为img_detail
,然后像这样使用它:
$('.fw .fp-ui').css("background-image", "url('"+data.img_detail+"')");
Using是使用 Javascript访问 JSON 数据key.some_value
的基本方法。
推荐阅读
- java - 如何在循环中更新多个变量
- java - Java中的自定义序列化
- ios - 如何以编程方式在 UIView 的中心添加文本?
- php - 努力将 PHP 数组输出为无序列的 HTML 列表
- java - 使用递归打印长度 X 的所有组合
- jenkins - Mercurial 插件配置面板未显示用于管理 Jenkins -> 配置系统
- c++ - 用 C++ 打印一个简单的数组
- javascript - Vue 列表在排序后不会“正确”重新渲染
- javascript - 我怎样才能得到两个输出?
- c# - 多次单击按钮时,无法使用 datetime.AddDays(7) 方法向所有 groupbox.text 标签多次添加一周