获取每个循环的迭代次数

Val*_*iia 0 javascript cypress

我得到以下代码,它循环遍历所有子项。我需要获取迭代次数,以便将其与子项总数进行比较。一旦循环处于最后一次迭代,就需要单击“下一步”按钮,以便打开新页面。

 cy.get('[data-automation="AssetGrids_GridItemContainer_div"]').each(
      ($element, index) => {
        cy.get('[data-automation="AssetGrids_GridItemContainer_div"]').then(
          (listing) => {
            const listingCount = Cypress.$(listing).length;
            cy.log('Number of elements: ' + listingCount);
          }
    );
    if (listingCount !=== index-1) {
    // Do some magic here if it's not the last iteration
       } 
  });
Run Code Online (Sandbox Code Playgroud)

我不确定这个解决方案是否正确,并且不会两次使用相同的定位器引发任何问题。有没有什么方法可以获取仅声明循环的找到元素的数量,以避免使用它?

cy.get('[data-automation="AssetGrids_GridItemContainer_div"]').then(
          (listing) => {
            const listingCount = Cypress.$(listing).length;
            cy.log('Number of elements: ' + listingCount);
          }
Run Code Online (Sandbox Code Playgroud)

小智 5

查看JQuery 选择器帮助 :not(:last)

:not(:last)在 a 中使用选择器.filter()将更改传递给 的列表.each()

cy.get('[data-automation="AssetGrids_GridItemContainer_div"]')
  .filter(':not(:last)')
  .each(($element) => {   // the last element is excluded
    ...
  })
Run Code Online (Sandbox Code Playgroud)

如果你想要一个else部分,:last-child可以在循环内使用

cy.get('[data-automation="AssetGrids_GridItemContainer_div"]')
  .each(($element) => {  
    if ($element.is(':last-child')) {

    } else {

    }
  })
Run Code Online (Sandbox Code Playgroud)

并且:nth-child(index)可以用于任意位置(注意索引是从 1 开始而不是从 0 开始)。

cy.get('[data-automation="AssetGrids_GridItemContainer_div"]')
  .each(($element) => {  
    if ($element.is(':nth-child(2)')) {   // 2nd item

    } else {

    }
  })
Run Code Online (Sandbox Code Playgroud)