问题
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