繁体   English   中英

无法访问嵌套循环元素

[英]Cannot access the nested loop element

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

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

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

根据您的评论,您尝试使用每个按钮访问每个类中的子div。

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

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

<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+'%');
});

演示小提琴

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

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM