0

我想获取从 HTML5 接收到的两项数据,并在 click 函数和其中的函数中使用它们。

我遇到了问题,所以这是我到目前为止的代码:

var test = [];

// This is a div class .quiz_list_row the ids are counted as #1 #2 #3...
$(".quiz_list_row").each(function(index){
    // Gets the data necessary
    //  It comes from data-quizlist-id (HTML5)
    $quiz_list_id = $(this).eq(index).data("quizlistId");

    //  It comes from data-quizlevel-reached (HTML5)
    $quiz_level_reached = $(this).eq(index).data("quizlevelReached");

    test[index] = $quiz_list_id;

    // testing
    alert("quiz_list_id: " +$quiz_list_id);
    alert("level: "+$quiz_level_reached);

    // click functions
    $(this).click(function(){

        // bla bla
        // alert(test[index]) ???
    });
});
4

2 回答 2

1

你在滥用.eq(). 试试这个(我已经删除了对 的调用.eq()):

var test = [];

    // This is a div class .quiz_list_row the ids (inside it) are counted as #1 #2 #3...
$(".quiz_list_row").each(function(index){

    // Gets the data necessary
               //  It comes from data-quizlist-id (HTML5)
    $quiz_list_id = $(this).data("quizlistId");
               //  It comes from data-quizlevel-reached (HTML5)
    $quiz_level_reached = $(this).data("quizlevelReached");

    test[index] = $quiz_list_id;

    // testing
    alert("quiz_list_id: " +$quiz_list_id);
    alert("level: "+$quiz_level_reached);

    // click functions
    $(this).click(function(){

          // bla bla
          // alert(test[index]) ???
    });
});

你可能只想要这个:

$(".quiz_list_row").click(function(){
    var $quiz_list_id = $(this).data("quizlistId");
    var $quiz_level_reached = $(this).data("quizlevelReached");

    alert("quiz_list_id: " +$quiz_list_id);
    alert("level: "+$quiz_level_reached);
});
于 2012-12-27T19:16:13.843 回答
0

在点击事件周围使用闭包

    // testing
    alert("quiz_list_id: " + $quiz_list_id);
    alert("level: " + $quiz_level_reached);

    // click functions
    (function(num) {
        $(this).click(function() {

            alert(test[num]) ? ? ?
        });
    })(index);

});​
于 2012-12-27T19:15:06.417 回答