gpt4 book ai didi

javascript - 如何遍历音频数组并在fa fa标签中播放

转载 作者:行者123 更新时间:2023-12-03 01:19:42 25 4
gpt4 key购买 nike

我有一段html代码:

                  <tr>
<th scope="row">1</th>
<td>Didn't love</td>
<td>4:18</td>
<td><i style="font-size:24px" class="fa love">&#xf144;</i></td>
</tr>
<tr>
<th scope="row">2</th>
<td>Keys</td>
<td>3:51</td>
<td><i style="font-size:24px" class="fa keys">&#xf144;</i></td>
</tr>
<tr>
<th scope="row">3</th>
<td>Smoking</td>
<td>5:12</td>
<td><i style="font-size:24px" class="fa smoking">&#xf144;</i></td>
</tr>
<tr>

我需要播放每首独特的歌曲,但要使用循环,避免了太多的JS代码行。我尝试了循环,但没有用。此选项有效:
       let songKeys = new Audio();
songKeys.src = 'audio/keys.mp3';
let songLove = new Audio();
songLove.src = 'audio/love.mp3';
let songSmoking = new Audio();
songSmoking.src = 'audio/smoking.mp3';



let keys = document.querySelector('.keys');
keys.addEventListener('click', function(){
if (songKeys.paused) {
songKeys.play();
} else {
songKeys.pause();
}
});
let love = document.querySelector('.love');
love.addEventListener('click', function(){
if (songLove.paused) {
songLove.play();
} else {
songLove.pause();
}
});
let smoking = document.querySelector('.smoking');
smoking.addEventListener('click', function(){
if (songSmoking.paused) {
songSmoking.play();
} else {
songSmoking.pause();
}

我试图创建var songs = new Array(..
src);
然后遍历 'document.querySelectorAll(.song)并嵌入 song[i].play();
关键是我的歌曲列表很大!

最佳答案

您可以检查我的解决方案。要使用此解决方案,您需要将song name作为类添加到icon中。

您的图标className应该看起来像:class="fa your_song_name"

console.clear();

const songIcons = document.querySelectorAll('i.fa');
songIcons.forEach(songIcon => {
songIcon.addEventListener('click', (e) => {
const icon = e.currentTarget;
const songName = icon.classList[1];
let song = new Audio();
song.src = `audio/${songName}.mp3`;

song.paused ? song.play() : song.pause();

// the selected Song
console.log(song);
})
})
i {
cursor: pointer;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.0.0/css/font-awesome.min.css" rel="stylesheet"/>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<tr>
<th scope="row">1</th>
<td>Didn't love</td>
<td>4:18</td>
<td><i style="font-size:24px" class="fa love">&#xf144;</i></td>
</tr>
<tr>
<th scope="row">2</th>
<td>Keys</td>
<td>3:51</td>
<td><i style="font-size:24px" class="fa keys">&#xf144;</i></td>
</tr>
<tr>
<th scope="row">3</th>
<td>Smoking</td>
<td>5:12</td>
<td><i style="font-size:24px" class="fa smoking">&#xf144;</i></td>
</tr>
<tr>

</body>
</html>

关于javascript - 如何遍历音频数组并在fa fa标签中播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61490800/

25 4 0