问题
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>
... 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.
回答1:
This is a for
loop solution.
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>
回答2:
Is this what you're looking for? Using jQuery: JSFiddle
for (var a = 0; a < $('audio').length; a++) { //Loops every audio element
$('audio').eq(a).attr('id', "audioNum" + a); //Adds ID from loop index
}
回答3:
I would do something like this:
const matches = document.querySelectorAll("audio");
With this method, we are storing in a constant named matches all the elements in the DOM that have the tag .
Then you can probably add the ID, as a unique identifier:
const matches = document.querySelectorAll("audio");
matches.forEach((match, i) => match.id = i);
In the example, I am adding as ID property the iteration number (from 0 to X) for every audio element in the DOM.
This is the output:
So now you have an array of every audio element in the DOM with a unique identifier ready to be used
来源:https://stackoverflow.com/questions/65659203/how-to-assign-identifiers-to-all-html-elements-of-a-particular-type