在页面执行期间,将组成一个字符串,其中包含需要作为 click 事件的处理程序执行的代码。该字符串可能如下所示:
var handler = '"myFunction1(12, 20);myOtherFunction();"';
或者
var handler = '"myFunction1(12, 20);"'
当我动态创建按钮并尝试在循环中附加事件时,它仅附加到最后一个按钮。我可以感觉到关闭问题,但我错过了什么?
这是代码。
var buttons = [],
arg1 = 12,
arg2 = 20;
var butt1 = { Text: 'Bye', onClick: "anotherFunction();" },
butt = { Text: 'Hello', onClick: "myNewFunction();" },
butt2 = { Text: 'Bye333' };
buttons.push(butt1);
buttons.push(butt);
buttons.push(butt2);
function myNewFunction() {
alert('my New Function');
};
function myCloseFunction(arg1, arg2) {
alert('close: ' + arg1 + ' other: ' + arg2)
}
function anotherFunction() {
alert('Say Goodbye');
}
window.onload = function () {
var buttonContainer = document.getElementById('controlDiv'),
closeOnClick = "myCloseFunction(" + arg1 + ", " + arg2 + ")",
button;
for (var i = 0; i < buttons.length; i++) {
buttons[i].onClick = (buttons[i].onClick == null) ? closeOnClick : (closeOnClick + ';\n' + buttons[i].onClick);
button = document.createElement("INPUT");
button.type = 'button';
button.onclick = new Function(buttons[i].onClick);
if (i > 0)
buttonContainer.innerHTML += ' ';
buttonContainer.appendChild(button);
}
};
HTML 页面很简单:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<script src="Script.js" type="text/javascript"></script>
</head>
<body>
<h1>hello</h1>
<div id="controlDiv"></div>
</body>
</html>
感觉到关闭问题,我尝试了各种选项来关闭任何变量,但没有成功。例如
button.onclick = (function (action, i) {
var name1 = 'hello' + i,
a123 = new Function('action', 'return function ' + name1 + '(){action();}')(action);
return a123;
} (new Function(buttons[i].onClick), i));