简体   繁体   English

jjery在ajax完成/完成后,要调用一个函数,该函数会执行越来越多次。 为什么?

[英]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. 我已经被困在这个问题上大约2天了。 My code ( JSFiddle here ) is thus: 我的代码( 这里JSFiddle )是这样的:

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. 第三次它会发射3次,依此类推。 Why is this happening? 为什么会这样? Am I making a basic logic error, or is this JavaScript doing something? 我是在做一个基本的逻辑错误,还是这个JavaScript做了什么?

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. 但随后ThiefMaster指出你也多次注册了事件处理程序。 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 请查看http://docs.jquery.com/Namespaced_Events

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM