-1

私のコード:

    <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) が消えるのに、2 回目の投稿リクエストが機能しないのはなぜですか? 可能ですか(リクエストインリクエスト)?

4

1 に答える 1

1

liクリックでエラーが発生していると思いますdata.player[i] is undefined

これは、クロージャー変数の使用によるものですi。その後、クリックイベントが発生iすると値data.player.lengthが設定されますが、data.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);
        });
    });
});
于 2013-03-28T04:39:35.370 に答える