0

次の JQuery コードがあります。

var test = new Array();

    $(".quiz_list_row").each(function(index){
            // Gets the data necessary to show game chosen
            $quiz_list_id = $(this).data("quizlistId");
            $quiz_level_reached = $(this).data("quizlevelReached");

                test.push($quiz_list_id,$quiz_level_reached);

            $(this).click(function(){
                alert("test: "+test);
            });

    });

div (html5 を使用してデータを送信):

<div class="quiz_list_row" data-quizlist-id="1" data-quizlevel-reached="5">
    <div class="inline quiz_list_cell" id="quiz_list_cell_row0_id1">Quiz 1</div>
    <div class="inline quiz_list_cell" id="quiz_list_cell_row0_id2">Current level: 5</div>
</div>
<div class="quiz_list_row" data-quizlist-id="2" data-quizlevel-reached="7">
    <div class="inline quiz_list_cell" id="quiz_list_cell_row1_id1">Quiz 2</div>
    <div class="inline quiz_list_cell" id="quiz_list_cell_row1_id2">Current level: 7</div>
</div>

問題は、ユーザーが特定の行をクリックしたときに配列内のデータを使用する方法を見つける必要があることtestです (使用したい$quiz_list_idand $quiz_level_reached)。

4

1 に答える 1

0

属性を抽出して配列に入れる特定の理由がない限り、目的を達成するために不必要な手順を踏んでいると思います。.data()これから複雑さを取り除きます。エレメントjQueryオブジェクトにアクセスできるときはいつでも、メソッドを使用してデータ属性にアクセスできます。そのうちの1つはクリックハンドラー自体内にあります。

var quizRows = $(".quiz_list_row");

quizRows.click(function(event) {

    var self = $(this);

    //As the element clicked on has it's data attributes defined
    //You would just need to retrieve it when the element is clicked on
    var id = self.data('quizlist-id'),
        level = self.data('quizlevel-reached');

    console.log("id is " + id);
    console.log("level is " + level);
}
于 2012-12-28T01:32:28.637 に答える