简体   繁体   English

带有jQuery each()的光滑滑块背景图像循环

[英]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. 如果我附加了img标签,则上述代码可以正常工作。 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. 我想要实现的目的是从JSON获取图像URL并将其用作背景滑块。 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追加中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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