【问题标题】:How i can get all att "href" of elements by 1 className? js [duplicate]我如何通过 1 个类名获取元素的所有 att“href”? js [重复]
【发布时间】:2021-01-31 10:03:40
【问题描述】:

例如我有代码:

<a class="link" href="https://example1.com">example1</a>
<a class="link" href="https://example2.com">example2</a>
<a class="link" href="https://example3.com">example3</a>

需要使用类“链接”获取元素的所有属性“href” 示例输出:

https://example1.com
https://example2.com
https://example3.com

我有脚本,但它总是得到第一个元素:

let i = 0;
let b = 3;
while (i < 3) { 
var href = $('.link').attr('href');
  console.log(href);
  i++;
}

如何在下一个元素处切换?

【问题讨论】:

    标签: javascript jquery web


    【解决方案1】:

    那是因为您一直选择相同的元素。您可以先获取所有项目并将它们存储在一个数组中。然后你可以使用一个循环来遍历你的数组并对所有的链接做一些事情。

    这是我在 JavaScript 中的做法:

    let links = document.getElementsByClassName("link");
    
    for (let i = 0; i > links; i++) {
      let href = links[i].getAttribute("href");
      console.log(href);
    }
    <a class="link" href="https://example1.com">example1</a>
    <a class="link" href="https://example2.com">example2</a>
    <a class="link" href="https://example3.com">example3</a>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-31
      • 1970-01-01
      • 1970-01-01
      • 2012-01-22
      • 1970-01-01
      相关资源
      最近更新 更多