You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击文本播放对应音频的JavaScript实现方案及代码修改咨询

解决点击不同文本播放对应音频的问题

Hey there! Let's fix this up for you. The issue right now is that your play() function is hardcoded to always use audio/audio_01.mp3—no matter which paragraph you click, it'll only ever play that one file. Here are two simple ways to make it work for both audio files:

方法1:给函数传递音频路径参数

这是最直接的修改方式,只需要让play()函数接收一个音频路径的参数,然后在点击时传入对应的路径:

修改你的JavaScript部分:

function play(audioPath) { 
  var audio = new Audio(audioPath); 
  audio.play(); 
} 

然后更新两个<p>标签的点击事件,传入各自的音频路径:

<p onclick="play('audio/audio_01.mp3');">The bandage was wound around the wound.</p> 
<p onclick="play('audio/audio_02.mp3');">farm was used to produce produce.</p>

方法2:使用data属性(更优雅的方式)

如果你不想在onclick里写重复的路径,可以用HTML的data-*属性来存储每个段落对应的音频路径,然后在函数里读取这个值:

修改JavaScript部分:

function play(event) { 
  // 获取点击元素的data-audio属性值
  var audioPath = event.target.dataset.audio;
  var audio = new Audio(audioPath); 
  audio.play(); 
} 

然后给每个<p>标签添加data-audio属性:

<p onclick="play(event);" data-audio="audio/audio_01.mp3">The bandage was wound around the wound.</p> 
<p onclick="play(event);" data-audio="audio/audio_02.mp3">farm was used to produce produce.</p>

两种方法都能实现你想要的效果,选哪个看你个人偏好啦!

内容的提问来源于stack exchange,提问作者Csaba Sárhegyi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 16:12:31