简体   繁体   中英

jQuery load() dynamic content with clicks get fired as many times as loaded

I load content via jQuery load() but for each time I load a given page, the clicks on the pages gets fired multiple times. Why??

Se the fiddle here: http://jsfiddle.net/ZUZ3L/ph3tH/2/

Simply put your click hander outsie of load :

$(document).ready(function() {
    function loadContent() {
        $(".ajaxContainer").load("http://fiddle.jshell.net/ #actions", function() {
            alert("Done");                
        });
    }

    $(".load").click(loadContent);
    loadContent();
});​

Updated Fiddle

Each time you load content, you execute this line:

$(".load").click(loadContent);

which adds a new event handler to the list of event handlers to execute whenever .load is clicked. You execute your function three times, now you have three identical handlers all triggering for each click.

because you are calling the function 2 times, try this:

$(document).ready(function() {
    function loadContent() {
        $(".ajaxContainer").load("http://fiddle.jshell.net/ #actions", function() {
            alert("Done");
        });
    }
    loadContent();
    $(".load").click(loadContent);

});

http://jsfiddle.net/ph3tH/4/

It's because you're adding the click event multiple times.

Every time your code runs, the click function is re-defined. When a click is redefined it won't replace the previous one, but instead will be added to the stack to be executed each time the "click" event occurs. This is applied to all events in jQuery.

As you are loading via AJAX the vars and events in the document are still persisted. Meaning that you are just adding layer on top of layer of function calls to be executed each time you run your ajax call

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