首页 > 解决方案 > 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>

标签: javascriptjquery

解决方案


如果response是 JSON 对象,您应该重命名img-detailimg_detail,然后像这样使用它:

$('.fw .fp-ui').css("background-image", "url('"+data.img_detail+"')");

Using是使用 Javascript访问 JSON 数据key.some_value的基本方法。


推荐阅读