在javascript中定位具有相同属性的多个元素

问题描述

我正在尝试使用 'data-caption' 属性定位所有 a 标签。

我尝试通过以下方式实现:

首先抓取所有 a 标签

  let links = document.querySelectorAll('a');

然后尝试收集他们的属性

 links.getAttribute('data-caption');

当我尝试记录属性时出现错误,指出“getAttribute”不是函数。

我尝试给一个 a 标记一个 ID,然后通过执行以下操作来定位该特定链接:

let link = document.getElementById('link').getAttribute('data-caption');

当我记录我的链接变量时,显示了该属性。这是我需要的,但对于我的所有链接。

我的计划是首先定位所有链接并获取它们的属性,然后创建一个循环以能够操作/显示这些属性。

这是我的一些 html,显示了我的 a 标签以供参考

<a id="link" href="photos/01.jpg" data-caption="I love hay bales. Took this snap on a drive through the countryside past some straw fields.">
     <img src="photos/thumbnails/01.jpg" alt="Hay Bales">
</a>

<a href="photos/02.jpg" data-caption="The lake was so calm today. We had a great view of the snow on the mountains from here.">
     <img src="photos/thumbnails/02.jpg" alt="Lake">
</a>

<a href="photos/03.jpg" data-caption="I hiked to the top of the mountain and got this picture of the canyon and trees below.">
    <img src="photos/thumbnails/03.jpg" alt="Canyon">
</a>

如果有人可以帮助/指出我正确的方向,谢谢!!!!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)