【问题标题】:Jquery - each() eq() click()Jquery - each() eq() click()
【发布时间】:2012-12-13 03:40:20
【问题描述】:

我想获取从 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]) ???
    });
});

【问题讨论】:

  • 你试过了吗?你有什么问题?
  • @SLaks 我试过了,我得到了第一个结果,但没有得到第二行,依此类推..
  • 我成功得到了结果。但它们是倒置的,这很奇怪,因为从 html 提交的“数据”具有有序数据!我会发送另一个问题。

标签: javascript jquery click each var


【解决方案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);
});

【讨论】:

  • $quiz_list_id$quiz_level_reached 未在第一个代码块上定义。
  • @RicardoLohmann 这是修改后的 OP 代码(只需删除 .eq(index))。第二块是修改/重构的解决方案。
  • 我真的需要每个,因为我想从每一行获取数据。感谢您提供有关 eq() 的提示!我仍然无法获得每一行的结果 =/
【解决方案2】:

在点击事件周围使用闭包

    // 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-07-01
    • 2013-09-28
    • 1970-01-01
    • 2011-03-31
    • 2016-08-09
    • 2011-05-10
    • 2011-06-10
    • 2013-02-10
    相关资源
    最近更新 更多