<div id='dependent'>
<input type="button" value="Add" id='btn' onclick='addfunction()' />
</div>
<script type="text/javascript">
var a = 1;
var b = 1;
var c = 1;
function addfunction() {
var c1 = document.createElement('input');
c1.type = "checkbox";
c1.id = "a" + a++;
var c2 = document.createElement('input');
c2.type = "checkbox";
c2.id = "b" + b++;
var c3 = document.createElement('input');
c3.type = "checkbox";
c3.id = "c" + c++;
var c4 = document.createElement('br');
document.getElementById("dependent").appendChild(c1);
document.getElementById("dependent").appendChild(c2);
document.getElementById("dependent").appendChild(c3);
document.getElementById("dependent").appendChild(c4);
// c1.onclick = dep();
// function dep() { alert(this.id); }
c1.onclick = function () { alert(this.id); };
}
</script>
当我这样调用函数时,
c1.onclick = function () { alert(this.id); };
它按预期工作。即,当我单击复选框时,会显示警报及其 ID。
但是如果我以这种方式调用函数,
c1.onclick = dep();
function dep() { alert(this.id); }
当我单击“添加”按钮(在调用 addfunction() 时)时,会出现警报。为什么?