Here i am created the button element with onclick function dynamically, I need to pass arguments through that onclick function to main function.but its not working I need some guidance...
var ar=["london","tokyo","india","pakistan"];
var cr=["green","blue","orange","pink"];
for(var j=0;j<ar.length;j++)
{
var but=document.createElement("button");
but.classList.add("divs");
but.onclick = function() {
myfun(ar[j],this,cr[j]);
}
but.textContent=ar[j];
document.getElementById("main").appendChild(but);
}
function myfun(city,elemt,color)
{
var butt=document.getElementsByClassName("divs");
for(var z=0;z<butt.length;z++)
{
butt[z].style.backgroundColor="";
}
document.getElementById(city).style.display="block";
elemt.style.backgroundColor=color;
}
var ar = ["london", "tokyo", "india", "pakistan"]; var cr = ["green", "blue", "orange", "pink"]; for (var j = 0; j < ar.length; j++) { let jj = j; //add this var but = document.createElement("button"); but.classList.add("divs"); but.id = ar[j]; // and dont forget this but.onclick = function () { myfun(ar[jj], this, cr[jj]); //must use jj when click j will = 4 } but.textContent = ar[j]; document.getElementById("main").appendChild(but); } function myfun(city, elemt, color) { var butt = document.getElementsByClassName("divs"); for (var z = 0; z < butt.length; z++) { butt[z].style.backgroundColor = ""; } document.getElementById(city).style.display = "block"; elemt.style.backgroundColor = color; }
<:DOCTYPE html> <html lang="en" xmlns="http.//www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title></title> </head> <body id="main"> </body> </html>
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.