2013-03-28 21 views
-1

我的代碼:的JavaScript(在後後)

<script type="text/javascript"> 
      window.onload = function() { 
        $.post("/Game/GetPlayers", function (data) { 
        for (var i = 0; i < data.player.length; i++) { 
         if ("@Session.SessionID" == data.player[i].AgainstId); 
         { 
          //some code 
         } 
         $("<li></li>").text(data.player[i].Name).on("click", function() { 
\*when i click - field hide */   $(this).hide(); 
         $.post("/Game/SetId", { name: data.player[i].Name },function(data2) { 
           alert(data2); 
          }); 
         }).prependTo("ol"); 
        } 
       }); 
      } 
     </script> 

爲什麼標籤(LI)消失當我點擊,但第二POST請求doesn'n工作?是否有可能(請求中的請求)?

+1

有一個','在if'聲明的'年底,將其刪除 – 2013-03-28 04:37:43

回答

1

我覺得li點擊導致一個錯誤data.player[i] is undefined

這是因爲封閉的可變i的用法。然後點擊事件發生i將具有值data.player.lengthdata.player[data.player.length]未定義。

$(function() { 
    $.post("/Game/GetPlayers", function(data) { 
     $.each(data.player, function(i, v) { 
      if ("@Session.SessionID" == v.AgainstId) { 
       // some code 
      } 
      $("<li></li>").text(v.Name).on("click", function() { 
       // when i click - field hide 
       // $(this).hide(); 
       $.post("/Game/SetId", { 
          name : v.Name 
         }, function(data2) { 
          alert(data2); 
         }); 
      }).prependTo("ol"); 
     }); 
    }); 
}) 

另一種選擇是使用事件委派

$(function() { 
    $.post("/Game/GetPlayers", function(data) { 
     $.each(data.player, function(i, v) { 
      if ("@Session.SessionID" == v.AgainstId) { 
       // some code 
      } 
      $("<li></li>").text(v.Name).data("player", 
        v.name).prependTo("ol"); 
     }); 
    }); 

    $('ol').on('click', 'li', function() { 
     var $this = $(this); 
     // when i click - field hide 
     // $(this).hide(); 
     $.post("/Game/SetId", { 
      name : $this.data('player') 
     }, function(data2) { 
      alert(data2); 
     }); 
    }); 
});