jQuery:Event Handler只运行一次

时间:2014-06-25 13:28:23

标签: jquery event-handling click

也许你听说过bxSlider。它是各种内容的常用jQuery滑块。我使用它,每次点击" next"或"之前"控制按钮。正文下方 - 标签我加载jQuery。以下脚本位于页面底部。

我的问题是,该功能' loadNext'只被叫一次。甚至没有触发.click。这是为什么?控制台中没有错误。

$(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--;

    }); 
});

1 个答案:

答案 0 :(得分:1)

问题是,

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;
    }
});