JQuery - Why this code to load an image from an external url not working?

javascript jquery css twitter-bootstrap

110 观看

2回复

56 作者的声誉

function applyimage(str){
   console.log("in apply image function");
   var url = 'base_url' + str ;
   url = ' url("' + url + '") ';
   console.log(url);
   $('.jumbotron').css({
    "background-image" : "url",
    "background-size" : "cover",
    "height" : "100%",
 });

When I log url into console it shows me the correct link. However this is not working.!

作者: Harsh Khajuria 的来源 发布者: 2017 年 9 月 15 日

回应 2


8

2393 作者的声誉

决定

Not add "" while you're using variable value

Code:

function applyimage(str){
    console.log("in apply image function");
    var url = 'base_url' + str ;
    url = ' url("' + url + '") ';
    console.log(url);
    $('.jumbotron').css({
        "background-image" : url,
        "background-size" : "cover",
        "height" : "100%",
});

When You write something in double quotes it means it will parse that as a string not a variable.

作者: Harsh Patel 发布者: 2017 年 9 月 15 日

0

9709 作者的声誉

Here you go with one more solution using ES6 template literals

function applyimage(str){ 
  $('.jumbotron').css({
    "background-image" : `url("base_url${str}")`,
    "background-size" : "cover",
    "height" : "100%",
  });
}

Your problem was in "background-image" : "url",.

Hope this will help you to solve the problem.

作者: Shiladitya 发布者: 2017 年 9 月 15 日
32x32