如何在JavaScript中为动态创建的onclick函数插入参数?

拉克希米·拉姆(Lakshmi Ram)

在这里,我使用onclick函数动态创建了button元素,我需要通过该onclick函数将参数传递给main函数。但是它不起作用,我需要一些指导...

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>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章