jQuery Delegate fails to run ajax
Here is my jQuery using delegate and ajax:
$(".tweets").delegate("#fav #submit", "click", function(){
var favid = $("#fav input#favid").val();
var favsave = 'favid=' + favid;
alert(favsave);
$.ajax({
type: "POST",
url: "fav.php",
data: favsave,
success: function() {
$('#fav').fadeOut(100);
}
});
return false;
});
The HTML:开发者_如何转开发
<div class='tweets'>
<ul class='entries'>
<li>
<form id='fav' method='post' class='favo' action=''>
<input style='display: none;' type='text' name='fav' id='fav' value='".$row["tweetid"]."' />
<input type='submit' value='Add to Favorites' name='submit' id='submit' />
</form>"
</li>
</ul>
</div>
There is another set of Ajax on the page that is constantly adding to the .entries list, these records that get appended pickup the click function, so that when I click on them the Alerts are shown but the Ajax part of the function doesnt work.
Any ideas? Would .live be better?
"doesn't work" is not the best of all descriptions.
Anyway, it makes no sense to use "absolute" selectors within an delegated event.
By querying $("#fav input#favid").val();
you would get results from all elements with that id
you would only get the first match (since ids
are assumed to be unique) (which would be unfortunate just because of multiple id tags
)
You should grab the target
property from the event object
to identify the elements which should get involved.
Example:
$(".tweets").delegate("#submit", "click", function(event){
var $self = $(event.target);
var favid = $self.siblings('#fav');
var favsave = 'favid=' + favid;
$.ajax({
type: "POST",
url: "fav.php",
data: favsave,
success: function() {
$self.closests('#fav').fadeOut(100);
}
});
return false;
});
It's probably not a good idea to have IDs
for elements which are created dynamically.
As mentioned, it's no valid HTML markup
to have multiple ID
tags. Should be classes I guess.
精彩评论