开发者

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

开发者 https://www.devze.com 2023-03-31 13:27 出处:网络
I\'ve been stuck on this issue for about 2 days. My code (JSFiddle here) is thus: var foo = function(){

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开发者_Go百科 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

0

精彩评论

暂无评论...
验证码 换一张
取 消