I have this bit of jQuery (excuse the horrible html appends – these will be eventually shortened!)
$(function () {
$(".follow").click(function () {
var element = $(this);
var I = element.data("userid");
var info = 'id=' + I;
var Something = $('#latestbettors tr[data-userid=' + I + ']').find('td:eq(0)').text();
$.ajax({
type: "POST",
url: "follow.php",
data: info,
success: function () {
$('.follow[data-userid=' + I + ']').fadeOut(200).hide();
$('.following[data-userid=' + I + ']').fadeIn(200).show();
if ($('#yourfollowers table tr > td:contains("You arent currently following any bettors")')) {
$('#yourfollowers table tr:contains("You aren\'t currently following any bettors")').remove();
}
if ($('#yourfollowers tr:contains("' + I + '")') && $('#yourfollowers tr > td:contains("' + Something + '")').length < 1) $('#yourfollowers table').fadeIn(200).append("<tr data-userid='" + I + "'><td>" + Something + "</td><td><a href='#'data-userid='" + I + "' class='following'></a><a href='#' data-userid='" + I + "' class='follow' style='display:none'></a></td></tr>");
}
});
return false;
});
});
$(function () {
$(".following").click(function () {
var element = $(this);
var J = element.data("userid");
var infos = 'id=' + J;
$.ajax({
type: "POST",
url: "unfollow.php",
data: infos,
success: function () {
$('.following[data-userid=' + J + ']').fadeOut(200).hide();
$('.follow[data-userid=' + J + ']').fadeIn(200).show();
$('#yourfollowers tr[data-userid=' + J + ']').fadeOut(200).remove();
if ($('#yourfollowers table tr').length == 0) {
$('#yourfollowers table').append('<tr><td>You aren\'t currently following any bettors</td></tr>');
}
}
});
return false;
});
});
I have two tables – latest bettors and following. The latest bettors table includes all of the newly signed up users with a follow button beside each (or following if the user is following them) … The following table includes all of the users the user is following with a following button beside each.
When the user clicks the follow button in the ‘latest bettors’ table it appends the user they have followed to the ‘following table’ – this works well. However when the user clicks on the ‘following’ button after this in the ‘following’ table – nothing happens? Why is this?
For dynamically generated elements, event should be delegated from one of static parents of the element or document object, you can use
onordelegatemethod:If you are using jQuery below 1.7 version you can also use
delegatemethod:Updated by @Exception:
And also you can use
But
liveis deprecated in latest versions of jQuery. It may work now if you are using old jQuery version, but it may not work with latest version of jQuery you use.