javascript 使用forEach或使用JS的for循环播放多个类或ID相同的音频文件

vyswwuz2  于 2023-01-24  发布在  Java
关注(0)|答案(1)|浏览(159)

我使用此代码:
HTML(尾风CSS):

<img src="https://static9.depositphotos.com/1049691/1080/i/450/depositphotos_10806368-stock-photo-fresh-apples.jpg" alt="" class="\>

联森:

function play() {
var audio = document.getElementById("audio");
audio.play();
}

function deny() {
var deny = document.getElementById("deny");
deny.play();

}

function give() {

变量give =文档. getElementById("give");网站();give.play();

}

我的give和deny函数只会播放一个音频文件,这很好。我如何避免重复使用这个播放块20次,而只是简单地使用一个for循环或forEach,而不是生成多个代码或DRY(不要重复自己)?
我尝试使用:
联森:

function play() {
    let playAll = document.querySelectorAll('audio');playAll.forEach((item) => {item.onclick = ()    =>  play();
 )}

HTML:项目1:

<img src="https://static9.depositphotos.com/1049691/1080/i/450/depositphotos_10806368-stock-         photo-fresh-apples.jpg" alt="" class="\>

<audio id="audio" src="dist\\assets\\audio\\I Want Apple.mp3"\>\</audio\>

第二项:

<img src="https://media.istockphoto.com/photos/marshmallow-crispy-rice-treat-against-white-     background-picture-id453551221?k=20&m=453551221&s=612x612&w=0&h=Q4-w0zgUvkTx56cpkLTz9eUH2UbNRGqiQyND528pDn4=" alt="" class="\>

<audio id="audio" src="dist\\assets\\audio\\I want rice krispy.mp3"\>\</audio\>

项目1和项目2都在播放"I want apple",而不是循环

col17t5w

col17t5w1#

对当前音频元素本身调用play

document.querySelectorAll('audio').forEach(
    item => item.addEventListener('click', () => item.play()));

相关问题