Having trouble with event binding for dynamically added stuff
I've a simple form that adds keywords and those keywords have delete button, both POST requests, done via ajax. delete request to non-dynamic keywords work via ajax, but dynamically added ones fallback to HTTP request. I read around and its narrowed down the problem to event binding.
var app = {
setupKeywordDeleteForm: function () {
// Was using regex plugin to find form which had ids like list_1, list_2 etc
// $("form:regex(id, list_*)").each ( function () {
$('li').each ( function () {
var $form = $(this);
$form.submit(function(e) {
e.preventDefault();
$.post($form.attr('action'), $form.serialize(), function() {
}, "script");
});
})
},
setupKeywordAddForm: function () {
var $form = $('#add_keywords');
$form.bind('submit', (function(e) {
e.preventDefault();
$.post(开发者_C百科$form.attr('action'), $form.serialize(), function() {
}, "script");
}));
},
}
jQuery(function () {
app.setupKeywordAddForm();
app.setupKeywordDeleteForm();
});
I've been reading learningjquery and messing with livequery plugin, but no avail. I understand the problem, just not able to solve it. Any help is appreciated. Also if you know a better way to define setupKeywordDeleteForm();
without looping, please let me know.
Edit:
The problem is when I add new keywords via ajax, the delete button on them falls back to HTTP request instead of submitting via ajax.
Managed to solve it thanks to this and this. Basically it calls setupNew on div.edit_list:last, i.e. the newly added keyword and sets up .post() on that.
var app = {
setupNew: function () {
var $form = $('.edit_list:last');
$($form).submit(function(e) {
e.preventDefault();
$.post($form.attr('action'), $form.serialize(), function() {
}, "script");
});
},
setupKeywordAddForm: function () {
var $form = $('#add_keywords');
$form.submit(function(e) {
e.preventDefault();
$.post($form.attr('action'), $form.serialize(), function() {
app.setupNew();
}, "script");
});
}
}
Yes, its a bit ugly, and I should probably DRY that up (I'm guessing I should create a general addKeyword function that accepts inputs and call that function for existing keywords and when new keyword is added?), but it works as of now. Thanks everyone for your help.
I'm not quite sure what the question is but I think $(selector).live()
(http://api.jquery.com/live/) is what you want. it will bind a event listener to all current and future elements with the selector.
精彩评论