0
$("#questions .question").each(function() {}

.question是一个 li,在.questionli 内部是另一个带有 class 的列表.answers,每个列表都有一个 li 的 class .answer

我已经尝试将它们定位在上述循环中,但没有运气:

$(this).$(".answer").each(function() {}

有谁知道如何使用这个在循环中定位每个答案 li ?

4

5 回答 5

3

$(this).find('.answer')或者$('.answer', this)

它们是等价的。来自 jQuery 源代码:

// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
    return this.constructor( context ).find( selector );
}
于 2013-03-06T13:40:54.247 回答
0

您可以传递上下文以应用选择器。在这种情况下,传递this将实现您想要的:

$("#questions .question").each(function() {
    $(".answer", this).each(function() { // Pass `this` as the context
    });
}
于 2013-03-06T13:41:48.060 回答
0
$("#questions .question").each(function(index, element) {
    $(element).find('.answer').each(function(index, element) {
        /* do stuff */
    });
});

http://api.jquery.com/jQuery.each/

于 2013-03-06T13:46:11.593 回答
0

使用$(this)

$("#questions .question").each(function() {
    console.log($(this)); // each .question li
}
于 2013-03-06T13:41:17.890 回答
0
$("#questions .question").each(function() {
    $(this).find(".answer").each( function() {
        //code here
    } );
}
于 2013-03-06T13:41:35.057 回答