我想在我的页面上动态插入新的轮播,我已经添加了一个简化的测试用例。唯一真正的区别是如何添加新的轮播,我的测试用例只是一个附加的字符串。但在我的项目中,这将是一个 Ajax 请求。
无论如何,如您所见,我在点击时销毁了所有轮播,然后在添加新轮播后,我尝试初始化新轮播和旧轮播。
问题是,新的不受影响。 但旧的仍然有效。
有什么想法可以让新的也工作吗?
测试用例:https://codepen.io/jsayner/pen/ab06bdabd3d74afc5e84cb7730d21b52
// external js: flickity.pkgd.js
var $carousel = $('.carousel').flickity();
$(document).on("click", "#button", function (e) {
$carousel.flickity('destroy');
var template = "<div class='carousel'>"
+ "<div class='carousel-cell'></div>"
+ "<div class='carousel-cell'></div>"
+ "<div class='carousel-cell'></div>"
+ "<div class='carousel-cell'></div>"
+ "<div class='carousel-cell'></div>"
+ "</div>";
$("body").append(template);
$carousel.flickity();
});
/* external css: flickity.css */
* { box-sizing: border-box; }
body { font-family: sans-serif; }
.carousel {
background: #FAFAFA;
}
.carousel-cell {
width: 66%;
height: 200px;
margin-right: 10px;
background: #8C8;
border-radius: 5px;
counter-increment: carousel-cell;
}
/* cell number */
.carousel-cell:before {
display: block;
text-align: center;
content: counter(carousel-cell);
line-height: 200px;
font-size: 80px;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/flickity@2/dist/flickity.pkgd.js"></script>
<link href="https://unpkg.com/flickity@2/dist/flickity.css" rel="stylesheet"/>
<button id="button" type="button">show carousel</button>
<div class="carousel">
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
</div>
你应该改变$carousel.flickity();
自$('.carousel').flickity();
变量$carousel只是您初始化轻弹时的实例,因此不适用于添加的元素。