简体   繁体   English

Ajax加载的内容事件多次触发

[英]ajax loaded content event triggered multiple times

I have a div in which I have a paragraph and a button like this: 我有一个div,其中有一个段落和一个像这样的按钮:

<div id="my_div">
    <p>This is a paragraph</p>
    <button class="my_btn">Click here!</a>
</div>

The content inside my div is loaded via Ajax. div中的内容是通过Ajax加载的。 Now let's say that I have something like this in the header of my page to test the button: 现在,我们在页面的标题中输入以下内容来测试按钮:

$(function(){

    $(document).on('click', '.my_btn', function(){

        alert('my button works!');        

    });

});

The problem I'm having is that everytime the content is loaded in my div with my paragraph and my button, when I click on my button I get my alert('my button works!') the same amount of time, meaning, if the content is loaded 100 times, I get my alert 100 times, any idea how I can fix this issue and why this is happening please? 我遇到的问题是,每次使用段落和按钮将内容加载到div中时,当我单击按钮时,都会收到相同时间的警报(“我的按钮有效!”),这意味着内容被加载了100次,我得到了100次警报,您知道如何解决此问题以及为什么会这样吗?

Thank you 谢谢

This is a bit of a hack but should work 这有点hack,但应该可以

 $(function(){

   $(document)
    .off()
    .on( 'click', '.my_btn', function(){

    alert('my button works!');        

  });

});

can you post the ajax call and how you are loading your div for a more detailed explanation. 您可以发布ajax调用以及如何加载div以获得更详细的说明。

That said, here is some sample code that seems to work fine. 就是说,这里有一些示例代码似乎运行良好。 fiddle here 在这里摆弄

<div id='data' style='display:none;'>
    <p>This is a paragraph</p>
    <button class="my_btn">Click here!</a></div>
<div id='target'></div>
<button class='load'>this load works</button>
$(document).ready(function() {
    $(document).on('click', '.my_btn', function(){
        alert('my button works!');        
    });       
    $('.load').click(function() {
        $('#target').html($('#data').html());
    });    
});

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

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