简体   繁体   中英

jquery after ajax complete /done , to call a function, the function will execute more and more times. why?

I've been stuck on this issue for about 2 days. My code ( JSFiddle here ) is thus:

var foo = function(){
    // The code in here will be execute more and more and more times
    $(element).hover(function() {
        console.log("buggie code run")
    })
}

var sliderShow = $(secondElement).bxSlider({
    onAfterSlide:function(currentSlideNumber) {
        $.ajax("/echo/html/").done(function() {
            foo();
        })
    }
})

My problem is the code will run more than once. For example, when you hover over the element it will fire the function once, but second time it will fire twice. The third time it will fire 3 times, and so on. Why is this happening? Am I making a basic logic error, or is this JavaScript doing something?

This means you are registering the event more than once, probably on each load. You should do so only once!

Hovering itself calls the function twice once on entry and once on exit.. try

var foo = function(){
    $(element).hover(function() {console.log("IN")},function() {console.log("OUT")});
}

But then as ThiefMaster pointed out you are also registering the eventhandler multiple times. In you slider, the second time you will add the event handler again and so on and on.

Look at http://docs.jquery.com/Namespaced_Events

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