0

我正在尝试访问嵌套循环中的元素。我已经使用 $(this) 很好地访问了第一个循环的循环元素,但是无法使用 $(this) 访问 secnod 元素。如何访问第二个元素?

$('.buttons').each(function(){
    width = 100 / $(this).length;
    $(this).each(function () {
        $(this).width = width + '%';
    });
});

上面的代码设置了第一个循环的第一个循环元素,而不是内部循环元素。

4

4 回答 4

3

根据您的评论,您正在尝试使用按钮访问每个班级内的子 div。

$('.buttons').each(function(){
    var children = $(this).find('div'), width = 100 / children.length;
    children.each(function () {
        $(this).width(width + '%');
    });
});
于 2013-08-20T17:33:31.573 回答
1

假设您的标记看起来像这样:

<div class="buttons">
    <div class="button"></div>
    <div class="button"></div>
    <div class="button"></div>
    <div class="button"></div>
</div>

我相信这就是你要找的,它会均匀地设置每个按钮的宽度,所以它们加起来是 100%;

$('.buttons').each(function(){
    var $buttons = $(this).find('.button');
    var width = 100 / $buttons.length;
    $buttons.width(width+'%');
});

演示小提琴

于 2013-08-20T17:43:31.757 回答
0

另一种方法是利用“每个”的参数。

$('.buttons').each(function(i, element) { ... });

这样,您可以在任何进一步的嵌套中使用 $(element) (除非稍后使用每个都被相同的参数名称覆盖)。

“i”是迭代器变量。如果它在第 3 个找到的元素上,我将是 2,第 4 将是 3,依此类推。

于 2013-08-20T17:39:52.583 回答
0

“this”始终是每个循环上下文中的交互器。因此,要引用外循环的交互器,您必须将其引用分配给变量。

$('.buttons').each(function(){
    var jqOuterThis = $(this);
    var outerWidth = 100 / $(this).length;
    $(jqOuterThis).each(function () {
        $(jqOuterThis).width(outerWidth + '%');
    });
});
于 2013-08-20T17:33:40.750 回答