如何遍历两个选定的元素?

时间:2019-07-11 10:30:13

标签: javascript jquery css-selectors

我想使用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 href一起访问 div.article 的文本然后将其推入href数组中。

2 个答案:

答案 0 :(得分:0)

请考虑以下内容:

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>

答案 1 :(得分:0)

再次,无需JQuery即可轻松实现:

var href = [];
var baseURL = "someURL";
var text, link;
for (const el of document.querySelectorAll("div.news > ul > li:nth-child(1) > a , div.article")) {
  switch (el.tagName) {
    case 'A':
      link = el.getAttribute('href');
      break;
    case 'DIV':
      text = el.textContent;
      break;
    default:
  }
};
href.push(`<a href="${baseURL}${link}">${text}</a>`);

console.log(href);
<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>