如何修复下一个复选框功能?

时间:2018-04-01 09:25:33

标签: jquery html

在下面的代码中,我想确保如果选中该复选框,变量mp3将包含MP3文件的URL,如果未选中该复选框,则表示不会。

我的代码如下:



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

if(checkBox.checked == true){

var mp3 = ('https://ia800503.us.archive.org/8/items/futuresoundfx-98/futuresoundfx-13.mp3');

var audio = new Audio('#mp3');
audio.play();

}else{

var mp3 = ('');

var audio = new Audio('#mp3');
audio.play();

}
}

<html>
<body>

<input type="checkbox" id="audio" onclick="audio()">

</body>
</html>
&#13;
&#13;
&#13;

问题是audio变量无法从mp3获取网址。

我该如何正确地做到这一点?

2 个答案:

答案 0 :(得分:0)

而不是onlick=audio()尝试onchange=audio()

您可能还想将元素添加为参数,而不是像以下那样通过id获取:

&#13;
&#13;
function audio(checkBox){
  if(checkBox.checked == true){

    var mp3 = ('https://ia800503.us.archive.org/8/items/futuresoundfx-98/futuresoundfx-13.mp3');
    var audio = new Audio('#mp3');
    audio.play();

    console.log("Audio will be played.");
  }else{

    var mp3 = ('');

    var audio = new Audio('#mp3');
    audio.play();
    console.log("Audio will be NOT be played.");

  }
}
&#13;
<html>
<body>
    <input type="checkbox" id="audio" onchange="audio(this)">
</body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我不确定你的问题。所以请看看并告诉我我的错误。

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

var audio = document.createElement("audio");
audio.src = 'https://ia800503.us.archive.org/8/items/futuresoundfx-98/futuresoundfx-13.mp3';

if (checkBox.checked) {
audio.play();

} else {
audio.pause();
audio.currentTime = 0;
}
}
<html>
<body>

<input type="checkbox" id="audio" onchange="audio()">

</body>
</html>

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

if (checkBox.checked) {

console.log("Audio will be played");

}
else 
{
console.log("Audio won't be played");
}
}
<html>
<body>

<input type="checkbox" id="audio" onchange="audio()">

</body>
</html>

如果你想两个都试试这个。

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

var audio = document.createElement("audio");
audio.src = 'https://ia800503.us.archive.org/8/items/futuresoundfx-98/futuresoundfx-13.mp3';

if (checkBox.checked) {
audio.play();

console.log("Audio will be played.");
} else {
audio.pause();
audio.currentTime = 0;
console.log("Audio won't be played.");
}
}
<html>
<body>

<input type="checkbox" id="audio" onchange="audio()">

</body>
</html>