简体   繁体   中英

jQuery does not work when reload the page content via ajax

I use Bootstrap to display a popover, until there is with all this code below everything works normal.

$(".emoticons").popover({
    html : true, 
    placement : 'bottom',
    animation : true,
    delay: { show: 100, hide: 500 },
    content: function() {return $('.emoticonimg').html();
    }
});

I only need to load the content of the page via ajax, then I changed the code because when I load the content dynamically I need to delegate events, changed the code and it looked like this:

$('body').on('click','.emoticons',function()
{
 $(".emoticons").popover({
    html : true, 
    placement : 'bottom',
    animation : true,
    delay: { show: 100, hide: 500 },
    content: function() {return $('.emoticonimg').html();
    }
 });
});

Now my troubles started. The code works however when I click the first time it does not work, so it works when I click more than once on the link. What to do?

It doesn't work the first time because the first click if firing off the body onclick handler which binds your popover.

Try something like this in your $(document).ready() function.

$(".emoticons").click(function(){

  $(this).popover({
    html : true, 
    placement : 'bottom',
    animation : true,
    delay: { show: 100, hide: 500 },
    content: function() {return $('.emoticonimg').html();
    }
 });

});

What's happening is that when you are clicking on the .emoticons and executing your popover function, it is at that moment that you are binding it to your click. That's why it doesn't work the first time, but it works afterwards. It starts listening to the click event after that.

Ideally, the solution is to run the .popover function when the new content is loaded (on your AJAX callback).

If you want to just copy paste my code and see if it works, you can do this:

$('body').on('click','.emoticons',function()
{
// Convert this element into a popover and then display it
 $(this).popover({
    html : true, 
    placement : 'bottom',
    animation : true,
    delay: { show: 100, hide: 500 },
    content: function() {
      return $('.emoticonimg').html();
    }
 }).popover('toggle');
});

But, I would NOT recommend this code specifically, since you are re-initializing your popover every time you click on it.

It's better and more clear if you bind all popovers after your AJAX request is done:

$.ajax( "BlaBlaBla.php" )
  .done(function() {
    // Convert all emoticons to popovers
    $(".emoticons").popover({
        html : true, 
        placement : 'bottom',
        animation : true,
        delay: { show: 100, hide: 500 },
        content: function() {
           return $('.emoticonimg').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