也许你听说过bxSlider。这是一个用于各种内容的常用jQuery滑块。我使用它,我希望每次点击"下一步"或"上一步"控制按钮时都会发生一些事情。在正文标签的正下方,我加载了jQuery。下面的脚本放在页面的底部。
我的问题是,函数'loadNext'只调用一次。连点击都没触发。为什么呢?控制台没有错误。
$(document).ready(function () {
// Initializing the slider, not that important for you, I guess
var viewWidth = $(window).width();
slider = $('#carouselSlider').bxSlider({
minSlide: 1,
maxSlide: 1,
slideWidth: viewWidth,
infiniteLoop: false,
hideControlOnEnd: true
});
// Initializing a 2nd slider inside the previous (main)slider. That works fine.
$('.tada').bxSlider({
startSlide: 0,
controls: false,
minSlide: 1,
maxSlide: 1,
slideWidth: 600,
pagerCustom: '.bx-pager-own'
});
// This function should be called. Works fine (once).
function loadNext() {
currentSlide = slider.getCurrentSlide();
var chainIDs = <?php echo json_encode($allChainIDs); ?>;
var dataToSend = {'currentSlide' : currentSlide, 'chainIDs[]' : <?php echo json_encode($allChainIDs); ?> } ;
//Main Images
$.ajax({
type: "POST",
url: "./backend/getImages.php",
data: dataToSend,
cache: false,
success: function(html){
$("#"+ chainIDs[currentSlide + 1]).html(html);
slider.reloadSlider({
startSlide: currentSlide
});
}
});
}
var steps = 0;
var prevsteps = 0;
// I assume, that the problem is lying here
$('a.bx-next').click( function() {
console.log("Clicked 'next'"); // that happens only once!!
steps++;
if(steps % 1 == 0 && steps > prevsteps){
loadNext();
prevsteps = steps;
}
});
$('a.bx-prev').click( function() {
steps--;
});
});
问题是
slider.reloadSlider({
startSlide: currentSlide
});
重新创建滑块元素。这会破坏click事件处理程序,因为原来的按钮被替换了。
您可以将其更改为。on(),它应该可以工作。例如,
$('body').on('click','a.bx-next',function() {
console.log("Clicked 'next'"); // that happens only once!!
steps++;
if(steps % 1 == 0 && steps > prevsteps){
loadNext();
prevsteps = steps;
}
});