jQuery events not happening after AJAX load?

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

提交回复
热议问题