javascript - 如何在javascript中向动态创建的onclick函数插入参数?
问题描述
在这里,我使用 onclick 函数动态创建了按钮元素,我需要通过该 onclick 函数将参数传递给主函数。但它不起作用我需要一些指导......
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>
推荐阅读
- django - 无法序列化 django 信号中的模型对象
- google-bigquery - BigQuery 中的映射(动态键)
- java - Spring忽略类加载器
- android - 查询为空时如何从 SearchView (Android) 中关闭键盘?
- flutter - 我想按其值订购我的 Firestore 数据
- mongoose - 具有 .every() 等效项的 Mongoose agreggate
- javascript - 如何从 React 中的类组件访问上下文变量?
- postgresql - PostgreSQL 触发函数语法错误帮助请求
- symfony - 如何为我的 Symfony Web 应用程序创建 YAML 配置?(不是捆绑)
- javascript - 使用 AJV 要求某些元素存在于数组中