jQuery events not happening after AJAX load?

前端 未结 8 681
别跟我提以往
别跟我提以往 2021-01-22 13:59

I have a website that will fade out a section of my website, load new content in, and fadeIn. There\'s a feature I had where a picture would get big when you click on it (it\'s

相关标签:
8条回答
  • 2021-01-22 14:21

    .click() is a shorthand of .bind('click'), which only binds to elements that are already in the page

    To bind events to current and future elements, you must use .live()

    // If the user makes a picture bigger
    $(".makePictureBig").live('click',function() {
         //code
    }); 
    

    Edit:

    As of jQuery 1.7, live is deprecated. You can use jQuery on:

    $(".makePictureBig").on('click', function() {
        //code
    }); 
    

    Or, for delegated event handlers:

    $("#wrapper").on('click', '.makePictureBig', function(){
        //code
    });
    
    0 讨论(0)
  • 2021-01-22 14:21

    This is because all your events that you write inside document ready will get executed only for the elements that are available at the time of page load.

    You will have to use .live() to bind events for all current and dynamically generated elements.

    Or you can bind the events once again in the success callback of your ajax function.

    0 讨论(0)
  • 2021-01-22 14:22

    The other answers are correct, but I will expand. When you bind an event with jQuery.bind (note that click, etc. are macros for bind) it only binds the event to DOM elements that exist at the current time. The jQuery selector scans the DOM for all elements that match the selector ($("#hoo").click() binds an event handler to any existing element with id="hoo").

    When elements are added to the DOM via ajax or other means, they do not automatically get all handlers bound to them. In order to do this, jQuery would have to scan the DOM for every event and apply the handler to any new element it found at any time. This is impractical.

    The two solutions are to apply the handlers to any elements loaded to the DOM later. For instance, change the 'click' function you have above to an actual function:

    function makePictureBig() {
       var theClassId = this.id;
       ...
    }
    

    Then say $(".makePictureBig").click(makePictureBig); ...and in your Ajax: $("#right_bar_wrapper").html(theRetrievedData) .find(".makePictureBig").click(makePictureBig);

    The second option is to use .live(), .delegate() or a plugin like .livequery().

    0 讨论(0)
  • 2021-01-22 14:27

    use

    $("****").live('click',function() {}); 
    
    0 讨论(0)
  • 2021-01-22 14:38

    Delegate is a better option than Live. You can delegate to a higher level element. You can even do:

    $('body').delegate('.makePictureBig', 'click', function() {
      //code
    });
    
    0 讨论(0)
  • 2021-01-22 14:40

    You will have to rebind the ajax events on any new content that you have loaded.

    Take your code that initializes the click event (ie the part that has the .click(...) in it) and put it in a seperate function.

    For example:

    function initImage() {
      ....click(function() {
    
      }
    }
    

    Then call that function both on document.ready and on your ajax success event.

    It might also be worth adding the following:

    $(".makePictureBig").unbind("click");
    

    just before:

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

    To ensure you do not attach the same event twice on each ajax post.

    Full example (this is done quickly and you might not need the logo to re-init, but it's safer to do it all in one place in case you change anything else with different ajax posts):

    $(document).ready(function() {
      initImages();
    }
    
    
    
    function initImages() {
    
    $(".makePictureBig").unbind("click");
    $(".makePictureBig").click(function() {
    var theClassId = $(this).attr('id');  
    var theID = theClassId.substring(6)
    var bigPictureComment = "#bigpicture_comment_" + theID;
    var littlePictureComment = "#littlepicture_comment_" + theID;
    var ffffd = document.getElementById(theClassId);
    var getBig = document.getElementById(bigPictureComment);
    var getLittle = document.getElementById(littlePictureComment);
    if (ffffd.style.width == "180px") {
        ffffd.style.width="430px";
        ffffd.style.marginBottom='10px';
        ffffd.style.cssFloat="left";
        $(littlePictureComment).hide();
        $(bigPictureComment).show();
    } else {
       ffffd.style.width="180px";
       ffffd.style.marginBottom='0px';
       $(bigPictureComment).hide();
       $(littlePictureComment).show();
    }
    });
    $("#logo").unbind("click");
    $("#logo").click(function() {
    $("#right_bar_wrapper").animate({ height: 'toggle', opacity: 'toggle' }, '200');
    var thePostData = "username=c";
    $.ajax({
      type: "POST",
      url: "http://myflashpics.com/v2/process_newsfeed.php",
      data: thePostData,
      success: function(theRetrievedData) {
        document.getElementById('right_bar_wrapper').innerHTML = theRetrievedData;
        $("#right_bar_wrapper").fadeIn("200");
        initImages();
      }
    });
    });
    
    }
    
    0 讨论(0)
提交回复
热议问题