简体   繁体   中英

javascript: set onclick function with a parameter for a button

I have created a button using javascript and now I want to give it a onclick. however I want the function to have a parameter i. the problem is that when I inspect the console the onclick function is just onclick=playAudio(i). I want it to be different for each value of i in the for loop, but because it is in brackets it just stays as i instead of the current number in the for loop. I hope I have explained this properly. some of the code is below to help you understand.

var i;
var audioMp3 = ["audio/Un", "audio/Deux", "audio/Trois", "audio/Quatre", "audio/Cinq", "audio/Six", "audio/Sept", "audio/Huit", "audio/Neuf", "audio/Dix"];

for(i = 0; i < audioMp3.length; i++{
    var audioBtn = document.createElement("BUTTON");
    audioBtn.setAttribute("onclick", "playAudio(i);";
}

我很确定这应该可行:

audioBtn.setAttribute("onclick", "playAudio("+i+");");

 var audioMp3 = ["audio/Un", "audio/Deux", "audio/Trois", "audio/Quatre", "audio/Cinq", "audio/Six", "audio/Sept", "audio/Huit", "audio/Neuf", "audio/Dix"]; for(var i = 0; i < audioMp3.length; i++){ var node = document.createElement("BUTTON"); var textnode = document.createTextNode(audioMp3[i]); node.appendChild(textnode); node.setAttribute("onclick", "playAudio("+i+");"); document.getElementById("element").appendChild(node); } function playAudio(i){ alert(i); } 
 <div id="element"></div> 

audioBtn.onclick = function(){playAudio(i)}

Create an array with all the possible values, loop through the values to create the buttons, each button should have their click event listener to play their own button's song.

I don't know your precise code but that is the pseudo-code to do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM