简体   繁体   中英

ajax loaded content event triggered multiple times

I have a div in which I have a paragraph and a button like this:

<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. 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?

Thank you

This is a bit of a hack but should work

 $(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.

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());
    });    
});

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