[英]Adding OnClick property to array javascript
我正在尝试将数组添加到我的简单JavaScript计算器的onclick按钮中。
我的第一个尝试是该process(text[i]);
在代码中,但根本不起作用。
因此,我将数组项转换为字符串,并提供给onclick函数。 然后它以一种奇怪的方式运行。
您能让我知道如何通过正确的类型吗?
var text = ["+", "-", "*", "/", "SQRT", "POW", "RNDM", "MAX", "MIN"];
for (var i = 0; i < text.length; i++) {
var child = document.createElement('button');
child.innerText = text[i];
child.value = text[i];
var temp = text[i].toString(); //<-- convert to make sure it is string
child.onclick = function () {
process(temp); //<-- it doesn't work properly, and it won't accept "process(text[i])???".
}
label1.appendChild(child);
}
document.body.appendChild(label1);
我必须离开计算机,但下面的设备几乎可以正常工作。 进入设置的onclick后, ops
是未定义的。 不知道为什么。 希望其他人可以以此为基础。
function process(operation) { alert(operation); } var ops = ["+", "-", "*", "/", "SQRT", "POW", "RNDM", "MAX", "MIN"]; for (var i = 0; i < ops.length; i++) { var child = document.createElement('button'); child.innerText = ops[i]; child.value = ops[i]; (child.onclick = function() { process(ops[i]); })(i) // label1.appendChild(child); document.body.appendChild(child); } // document.body.appendChild(label1);
正如@adeneo早已解释的那样,问题在于所有onclick
处理程序都使用相同的temp
变量。 为每次迭代提供单独作用域的另一种方法是使用forEach
方法而不是for
循环:
["+", "-", "*", "/", "SQRT", "POW", "RNDM", "MAX", "MIN"].forEach(function(text) {
var child = document.createElement('button');
child.innerText = text;
child.value = text;
child.onclick = function () {
process(text);
}
label1.appendChild(child);
});
范例: http : //jsfiddle.net/kq1mpm3g/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.