jQuery只部分处理Click函数

我有这个jQuery(借口可怕的html附加 – 这些最终会缩短!)

$(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("" + Something + ""); } }); 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('You aren\'t currently following any bettors'); } } }); return false; }); }); 

我有两张桌子 – 最新的投注者和跟随者。 最新的投注者表包括所有新注册的用户,每个用户旁边都有一个跟随按钮(如果用户跟随他们,则跟随他们)…下表包括用户所关注的所有用户,每个用户旁边都有一个按钮。

当用户点击“最新投注者”表中的跟随按钮时,它会将他们所关注的用户附加到“下表”中 – 这很有效。 但是,当用户在“关注”表中单击“跟随”按钮后 – 没有任何反应? 为什么是这样?

对于动态生成的元素,事件应该从元素或文档对象的静态父类之一委托,您可以使用ondelegate方法:

 $(document).on('click', '.following', function(){ 

如果您使用1.7版以下的jQuery,您还可以使用delegate方法:

 $(document).delegate('.following', 'click', function(){ 

由@ Exception更新:

而你也可以使用

 $('.following').live('click', function(){ 

但是在最新版本的jQuery中不推荐使用live 。 如果您使用旧的jQuery版本,它现在可能会工作,但它可能不适用于您使用的最新版本的jQuery。