How do you make jQuery bind events to elements loaded via Ajax?

烂漫一生 提交于 2019-11-28 06:15:30

问题


I'm using the .load() function to load a section of html that has some jQuery functionality that is bound to a certain class. =/

thoughts?


回答1:


Use live events:

$('.className').live(function(event) {
   ...
}

jQuery keeps a repository of all live selectors such as .className in this case. And it adds a handler to the document to listen for events that bubble up to the document. This special handler then basically runs through all the live selectors and forwards the event to those elements that match the live selectors, if any.

If any of the intermediate event handlers intercept the event and stop it from further propagating before it reaches up to the document, the live handlers will not be executed.




回答2:


If you are using a click event this will be your syntax:

   $('a.myClass').live("click", function() {

        // do something here

    });



回答3:


You need to use JQuery's live function. This allows you to:

Attach a handler to the event for all elements which match the current selector, now or in the future.




回答4:


You can use the on() function.

Like so:

$(".existingElement").on('click', '.addedByAjax .className', function(){
  // ... do whatever
}

Note that existingElement has to exist in the moment when this piece of code is going to run. So you always have to bind to an element, to which you're going to load stuff by ajax into, and use the second selector (the one in the on() function) to match whatever is added.




回答5:


You have to manually bind the events after you set the html.

$.post('ajax/test.html', function(data) {
  $('.result').html(data);
  $('.result a').click(function() {
    alert('click');
  });
});

Additionally you can use live to help with it.



来源:https://stackoverflow.com/questions/2413797/how-do-you-make-jquery-bind-events-to-elements-loaded-via-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!