【发布时间】:2021-07-20 17:03:59
【问题描述】:
我正在尝试使用 '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>
如果有人可以帮助/指出正确的方向,谢谢!!!!
【问题讨论】:
-
document.querySelectorAll("a[data-caption]")- 将获取所有带有 data-caption 属性的锚标签。它返回一个元素数组,因此您可以遍历它并使用 getAttribute 读取每个条目的值。 -
谢谢,我明白了!这回答了我的问题,非常感谢! @LukeBriggs
标签: javascript html loops getattribute