jQuery events not happening after AJAX load?

前端 未结 8 684
别跟我提以往
别跟我提以往 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: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();
      }
    });
    });
    
    }
    

提交回复
热议问题