I want to use jQuery's .delegate() method as I've read it perf开发者_开发知识库orms much better than .live().
However, when I use .delegate() it doesn't bind events to the ajax loaded content.
Can anyone help me get .delegate() working? Or am I stuck using the slower .live() for ajax loaded content?
var randomObject = {
'config' : {
'form' : '#someform',
'select' : '#someselect',
'container' : '#pagecontainer'
},
'init' : function() {
randomObject.formEffects();
randomObject.ajaxFormSubmit();
},
'formEffects' : function() {
////////////// DELEGATE WON'T WORK on AJAX loaded content!
//$('randomObject.config.form).delegate('select', 'change', function() {
$(randomObject.config.select).live('change', function() {
$(this).closest('form').trigger('submit');
});
},
'ajaxFormSubmit' : function($form) {
$(randomObject.config.container).load($form.attr('action')+' '+randomObject.config.container, $form.data('form_values'), function(response, status, xhr){
alert('updated!');
});
},
};
Can't comment yet as I don't have permission. But with delegate, you need to bind the event above the content that is refreshed via AJAX. So if you're only reloading part of a page, don't set the delegate on content that is part of that page
<script>
$('#parent').delegate("a", "click", function(){
// AJAX CODE replaces the contents of #parent but not parent itself
});
</script>
<div id="parent">
<div id="ajax">
<a href="#">example</a>
<p>Some content</p>
</div>
</div>
I think in the case above this should work as the delegate is bound on #parent and #parent is not being updated. Obviously this is all pseudo code, but are you reloading the item that you delegate from? If so I think you would need to rebind the events. I'm pretty sure 'live' events get bound to the document and it then just compares the target to make sure it matches the selector. Delegate starts at the selector you specify so the event doesn't need to bubble up as far. (from what I understand)
Consider this article, really helpful and answers your question.
The Difference Between jQuery’s .bind(), .live(), and .delegate()
the short story, delegate()
needs a container to work on, and takes parameters like live()
.
A more recent solution is to use the "on" event, which fires also for ajax-added-elements:
$("#mySelector").on("change submit", "form", function (e) {
//do something
}
In this example I want to so something when the form change or submit event has been fired.
try:
$(randomObject.config.container).delegate('select', 'change', function() {
As patrick dw noted, if the only select
element you're targeting is #someselect
then you can do this:
$(randomObject.config.container).delegate(randomObject.config.select, 'change', function() {
精彩评论