我试图通过单击按钮在2首歌曲之间交换。我只需更改src就可以成功交换歌曲,但是当我使用if语句时,控件“闪烁”,这意味着if else语句中必须有一个错误。
HTML
<div id = "audioplayer">
<p id="songname">Listen to Sisyphus by Have A Nice Life</p>
<audio id = "song"
controls
src="Untitled/10%20Sisyphus.mp3">
Your browser does not support the
<code>audio</code> element.
</audio>
</div>
<button onclick="myFunction()">Click to change songs</button>
JS:
function myFunction() {
if(document.getElementById("song").src === "Untitled/10%20Sisyphus.mp3") {
document.getElementById("songname").innerHTML = "listening to track03.mp3";
document.getElementById("song").src = "test.mp3";
}
else{
document.getElementById("songname").innerHTML = "Listen to Sisyphus by Have A Nice Life";
document.getElementById("song").src = "Untitled/10%20Sisyphus.mp3";
}
}
答案 0 :(得分:2)
尽管您可以为.src
设置相对路径(例如"Untitled/10%20Sisyphus.mp"
),但是访问.src
属性将为您提供 full 路径:< / p>
const song = document.getElementById("song");
song.src = "test.mp3";
console.log(song.src);
<audio id="song" controls src="Untitled/10%20Sisyphus.mp3"></audio>
因此,您只需要用完整路径替换测试,例如:
function myFunction() {
if (document.getElementById("song").src === "https://example.com/Untitled/10%20Sisyphus.mp3") {
// ...
实时代码段(可以运行HTML,但没有实际声音):
function myFunction() {
const song = document.getElementById("song");
const songname = document.getElementById("songname");
if (song.src === "https://stacksnippets.net/Untitled/10%20Sisyphus.mp3") {
songname.innerHTML = "listening to track03.mp3";
song.src = "test.mp3";
} else {
songname.innerHTML = "Listen to Sisyphus by Have A Nice Life";
song.src = "Untitled/10%20Sisyphus.mp3";
}
}
<div id="audioplayer">
<p id="songname">Listen to Sisyphus by Have A Nice Life</p>
<audio id="song" controls src="Untitled/10%20Sisyphus.mp3">
Your browser does not support the
<code>audio</code> element.
</audio>
</div>
<button onclick="myFunction()">Click to change songs</button>