简体   繁体   中英

Slick Slider background image loop with jQuery each()

Having problem to looping the background image in slick slider. Please see the code below.

var json = [
  { "img_url": "https://via.placeholder.com/500x500?text=1" },
  { "img_url": "https://via.placeholder.com/500x500?text=2" },
  { "img_url": "https://via.placeholder.com/500x500?text=3" }
];

$.each(json, function () {
  var image = this["img_url"];
  console.log(image);
  $("#test").append(
    "<div class='slideBG'><img src=" + image + "></div>"
  );
}); // each ENDS

// initialize the slick slider
$("#test").slick({
  autoplay: true,
  autoplaySpeed: 5000,
  dots: false,
  arrows: false,
  infinite: true,
  fade: true
});

Above code works fine if I append the img tag. But If I try with...

$(".slideBG").css("background", "url('" + image + "')");

It only displays the last image as a background withouth looping the other images. What I'm trying to achieve to get the image url from the JSON and use it as the background slider. I'll appreciate if someone could help me with this.thanks

Figured it out. Added the background style attribute directly into the div append as below.

 <div style="background:url(' + image + ')" class="slideBG"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM