Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/478.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jquery每个循环中的每个循环_Javascript_Jquery_Html - Fatal编程技术网

Javascript jquery每个循环中的每个循环

Javascript jquery每个循环中的每个循环,javascript,jquery,html,Javascript,Jquery,Html,我有一些div用作容器,我想循环它们,然后循环其中的项目 所以不是$('.stackContainer.stackItem')。每个()都是这样的: // setup stacks $('.stackContainer').each(function(containerIndex) { //console.log($(this)); console.log(containerIndex); $(this).('.stackItem').each(function(ite

我有一些div用作容器,我想循环它们,然后循环其中的项目

所以不是
$('.stackContainer.stackItem')。每个(
)都是这样的:

// setup stacks
$('.stackContainer').each(function(containerIndex) {
    //console.log($(this));
    console.log(containerIndex);

    $(this).('.stackItem').each(function(itemIndex) {
        console.log(itemIndex);     
    }
});
只有这样才能工作。 这怎么可能呢?

试试
find()
方法:

$('.stackContainer').each(function(containerIndex) {
    //console.log($(this));
    console.log(containerIndex);

    $(this).find('.stackItem').each(function(itemIndex) {
        console.log(itemIndex);     
    }
});
尝试
find()
方法:

$('.stackContainer').each(function(containerIndex) {
    //console.log($(this));
    console.log(containerIndex);

    $(this).find('.stackItem').each(function(itemIndex) {
        console.log(itemIndex);     
    }
});
试一试

试一试


正如其他答案所示,有很多方法可以做到这一点。这里有一个解决方案:

或者,如果您只想按照
.stackItem
div在页面上的显示顺序迭代所有
.stackItem
div,而实际上您并不关心父
.stackContainer
div,那么您只需执行
$('.stackItem')。每个(函数(索引){…};


嵌套在
.stackItem
div上迭代的循环的原因是,如果您希望
itemIndex
变量在每次切换父容器时重置为零。

许多方法都可以做到这一点,如其他答案所示。以下是一个解决方案:

或者,如果您只想按照
.stackItem
div在页面上的显示顺序迭代所有
.stackItem
div,而实际上您并不关心父
.stackContainer
div,那么您只需执行
$('.stackItem')。每个(函数(索引){…};


嵌套迭代
.stackItem
div的循环的原因是,如果希望每次切换父容器时
itemIndex
变量重置为零。

出于性能原因,如果集合可能具有任何大小,则应避免使用jQuery的each()


另一方面,出于性能原因,如果集合可能有任何大小,则应避免使用jQuery的each()


打开浏览器的开发人员控制台,您将知道代码错误的原因。打开浏览器的开发人员控制台,您将知道代码错误的原因。
$(".stackContainer").each(function(stackIndex) {
    $(this).children().css('class', '.stackItem').each(function(itemIndex) {
        $(this).html($(this).html() + "=>" + itemIndex);
    });
});​