1

私はこの少しの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("<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;
  });
});

最新のベッターとフォロー中の 2 つのテーブルがあります。最新のベッターの表には、新しくサインアップしたすべてのユーザーが含まれており、それぞれの横にフォロー ボタンがあります (または、ユーザーがフォローしている場合はフォローしています)。

ユーザーが「latest bettors」テーブルのフォロー ボタンをクリックすると、フォローしているユーザーが「following table」に追加されます。これはうまく機能します。ただし、ユーザーが「次の」テーブルでこの後に「次の」ボタンをクリックすると、何も起こりませんか? どうしてこれなの?

4

1 に答える 1

2

動的に生成された要素の場合、要素またはドキュメント オブジェクトの静的な親の 1 つからイベントを委任する必要があります。onまたはdelegateメソッドを使用できます。

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

バージョン 1.7 未満の jQuery を使用している場合は、次のdelegateメソッドも使用できます。

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

@例外によって更新:

また、使用することもできます

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

ただしlive、最新バージョンの jQuery では非推奨です。古いバージョンの jQuery を使用している場合は動作する可能性がありますが、最新バージョンの jQuery を使用している場合は動作しない可能性があります。

于 2012-12-29T11:33:50.820 に答える