如何为特定类型的所有HTML元素分配标识符? [英] How to assign identifiers to all HTML elements of a particular type?
问题描述
我的网站嵌入了来自RSS提要的帖子,其中一些帖子包含< audio>
元素.在一个单独的JS文件中,我希望能够基于页面的src属性为页面上的每个< audio>
元素分配一个唯一的标识符,以便可以分别处理它们.当然,我事先不知道会有多少< audio>
元素,也不知道它们的src属性的名称是什么.所以基本上我会有这样的东西:
My site embeds posts from an RSS feed, and some of these posts contain <audio>
elements. In a separate JS file, I want to be able to assign each <audio>
element on the page a unique identifier based on their src attribute so that they can be handled separately. Of course, I don't know in advance how many <audio>
elements there will be, nor what the names of their src attributes will be. So basically I will have something like this:
<audio src="1.mp3"></audio>
<audio src="2.mp3"></audio>
<audio src="3.mp3"></audio>
...
<audio src="X.mp3"></audio>
...预先未知mp3的文件名.因此,我希望我的JS文件能够扫描HTML,并且每次遇到< audio>
元素时,都将其添加到具有某种唯一标识符的列表中,这样它们就可以被告知.
... where the filenames of the mp3s are unknown in advance. So I want my JS file to be able to scan through the HTML, and each time it encounters an <audio>
element, add it to a list with some sort of unique identifier so that they can all be told apart.
推荐答案
这是 for
循环解决方案.
let audio = document.querySelectorAll('audio');
for (let i = 0; i < audio.length; i++) {
audio[i].setAttribute('id', i);
console.log(audio[i]);
}
<audio src="1.mp3"></audio>
<audio src="2.mp3"></audio>
<audio src="3.mp3"></audio>
这篇关于如何为特定类型的所有HTML元素分配标识符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!