如何使此代码更高效或更短。我觉得有太多的重复功能。有没有办法让这一切都在一个更短的时间?
<html>
<body>
<button onclick="myFunction()">Audio 1</button>
<button onclick="myFunction2()">Audio 2</button>
<button onclick="myFunction3()">Audio 3</button>
<script>
function myFunction() {
var a = new Audio('Link1');
a.play();
}
function myFunction2() {
var b = new Audio('Link2');
b.play();
}
function myFunction3() {
var c = new Audio('Link3');
c.play();
}
</script>
</body>
答案 0 :(得分:4)
您可以为链接的函数添加参数。
HTML:
<button onclick="playAudio('link1')">Audio 1</button>
<button onclick="playAudio('link2')">Audio 2</button>
<button onclick="playAudio('link3')">Audio 3</button>
使用Javascript:
function playAudio(link) {
var audio = new Audio(link);
audio.play();
}
答案 1 :(得分:2)
使用函数调用参数,请尝试以下操作:
<button onclick="doPlay(1)">Audio 1</button>
<button onclick="doPlay(2)">Audio 2</button>
<button onclick="doPlay(3)">Audio 3</button>
function doPlay(index) {
var a = new Audio('Link' + index);
a.play();
}