简体   繁体   English

如何在 foreach 循环中使用 foreach 循环?

[英]How can I use foreach loop inside a foreach loop?

I need to find all elements in the page by class and click them, then in each element, I need to find all other elements by class and click, how can I do that in an easy way?我需要按类查找页面中的所有元素并单击它们,然后在每个元素中,我需要按类查找所有其他元素并单击,我该如何简单地做到这一点? I tried using foreach loop inside foreach loop, but it did not work properly我尝试在 foreach 循环中使用 foreach 循环,但它无法正常工作

var select2arrow = driver.FindElements(By.ClassName("select2-arrow"));
foreach (IWebElement element in select2)
{
    try
    {
        element.Click();
        var select2title = driver.FindElements(By.ClassName("title"));
        foreach (IWebElement element in select2title )
        {
            try
            {
                element.Click();
            }
        }
    }
    catch (Exception ex)
    {
         if (TestRunner.LogTestReports)
         {
                    driver.SaveScreenshot(ex);
         }
    }
}

The problem originates from the fact you are using the same name element as an iterator for both of the loops.问题源于您使用相同的名称element作为两个循环的迭代器。 You also break the try-catch block.您还破坏了 try-catch 块。

In addition to @Gnqz answer, in foreach (IWebElement element in select2) you iterate over select2 when the elements are in select2arrow .除了@Gnqz 答案之外,在foreach (IWebElement element in select2) ,当元素在select2arrow时,您会遍历select2

You also don't have catch in the inner try block.您也没有在内部try块中catch

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

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