首页 > 解决方案 > 如何循环通过两个选定的元素?

问题描述

我想循环使用HTML页面的两个类,jQuery并且我正在尝试使用每个循环,但问题是我在哪里可以访问回调函数中的两个选定类?

var href = [];

  $("div.news > ul > li:nth-child(1) > a , div.aticle  ").each((el, i) => {
      var baseURL = "someURL";
      var link = baseURL + $(i).attr("href");
      var text =
         /* i want to access text() of div.article along with the href 
           of the div.news in this loop and then push it into href array */
      href.push({
        link
      });
  });

我想在这个循环中使用 jquery 的 text() 函数以及div.news访问 div.article文本,然后将其推送到数组中。hrefhref

标签: jquery

解决方案


考虑以下:

var href = [];
var text = [];
$("div.news > ul > li:nth-child(1) > a, div.article").each((el, i) => {
  if ($(i).is(".article"))
    text.push($(i).text());
  else {
    var baseURL = "someURL";
    var link = baseURL + $(i).attr("href");
    href.push(link);
  }
});
console.log(href, text)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="news">
  <ul>
    <li>
      <a href="www.google.com"></a>
    </li>
  </ul>
  <ul>
    <li>
      <a href="www.bing.com"></a>
    </li>
  </ul>
  <ul>
    <li>
      <a href="www.duckduckgo.com"></a>
    </li>
  </ul>
</div>
<div class="article">
  text
</div>


推荐阅读