Search code examples
jqueryjquery-load

when .load() same page, click trigger twice in jquery


this is my main page html:

<script type="text/javascript" src="js/jquery.min.js"></script>
<div><a href="#" class="MyClick">Parent Click</a></div>
<div class="content"></div>
<script>
  $(document).ready(function(){ 
    $('.MyClick').click(function(){
       $('.content').load('page2.html');
    }); 
  })
</script>

and this is page2.html

<a href="#" class="showoff">Child Click</a>
<script type="text/javascript">
 $(document).ready(function(){      
    $('.showoff').live('click',function(){
        console.log('I Clicked');
    });     
 });
</script>

when link parent click clicked, load page2.html into div.content and when child click cliked print in console firebug once..

but my problem is when I click again parent click and click again child click, in console print twice however I click once, it's like page2.html before not yet remove from DOM and child click in page2.html before fired together with a new one..

I want to how many time I load page2.html it's not print multiple line when I just click once Child click


Solution

  • Every time you load page2.html you register a delegate click handler for .showoff since you use .live()(which is deprecated by the way, use .on() or .delegate() for version < 1.7), that's why you get multiple prints per clicks.

    Are you using live for a specific purpose? Cause it seems unnecessary to me, just use a handler on the element itself.

    <a href="#" class="showoff">Child Click</a>
    <script type="text/javascript">
     $(document).ready(function(){      
        $('.showoff').on('click',function(){
            console.log('I Clicked');
        });     
     });
    </script>