简体   繁体   English

带有点击的jQuery load()动态内容被加载次数被触发

[英]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. 我通过jQuery load()加载内容,但是每次加载给定页面时,页面上的点击都会被触发多次。 Why?? 为什么??

Se the fiddle here: http://jsfiddle.net/ZUZ3L/ph3tH/2/ 此处的小提琴是: http : //jsfiddle.net/ZUZ3L/ph3tH/2/

Simply put your click hander outsie of load : 只需将您的点击处理结果放到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. 这会在事件处理程序列表中添加一个新的事件处理程序,以便在单击.load执行。 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/ http://jsfiddle.net/ph3tH/4/

It's because you're adding the click event multiple times. 这是因为您要多次添加click事件。

Every time your code runs, the click function is re-defined. 每次运行代码时,都会重新定义click函数。 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. 这适用于jQuery中的所有事件。

As you are loading via AJAX the vars and events in the document are still persisted. 通过AJAX加载时,文档中的var和事件仍然保留。 Meaning that you are just adding layer on top of layer of function calls to be executed each time you run your ajax call 这意味着您只是在每次运行ajax调用时要执行的函数调用之上添加一层

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

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