2015-11-25 73 views
0

的JavaScript看起來就像這樣:如何正確地將此代碼轉換爲for循環?

function playsound(button) { 

switch(button){ 
case "button1": 
    switch(soundbank){ 
     case 0: 
      document.getElementById("audio1").load(); 
      document.getElementById("audio1").play(); 
      break; 
     case 1: 
      ... 
      ... 
case "button2": 
    switch(soundbank){ 
     case 0: 
      document.getElementById("audio2").load(); 
      document.getElementById("audio2").play(); 
      break; 
case "button3": 
    switch(soundbank){ 
     case 0: 
      document.getElementById("audio3").load(); 
      document.getElementById("audio3").play(); 
      break; 
case "button4": 
    switch(soundbank){ 
     case 0: 
      document.getElementById("audio4").load(); 
      document.getElementById("audio4").play(); 
      break; 
case "..." 
    ... 
    ... 
}} 

HTML這樣的:

<button onclick="playsound(this.id)" id="button1" </button> 
<button onclick="playsound(this.id)" id="button2" </button> 
<button onclick="playsound(this.id)" id="button3" </button> 
<button onclick="playsound(this.id)" id="button4" </button> 

<audio id="audio1"> 
    <source src="audio1.wav"> 
</audio> 
<audio id="audio2"> 
    <source src="audio2.wav"> 
</audio> 
<audio id="audio3"> 
    <source src="audio3.wav"> 
</audio> 
<audio id="audio4"> 
    <source src="audio4.wav"> 
</audio> 

我願把大部分的成圈而不是1000線開關盒,並且如果其他人,但我可以解決不了。有什麼建議麼?非常感謝。

回答

0

它是令人驚訝的,你可以用字符串操作。

document.getElementById("audio"+button.substring(6)).load();