70行中的on click事件(ob.addEventListener(“click”,onCl1(idTable [0],idTable));)无理由被触发。我尝试了其他一些方法,但仍然有同样的反应。我提出了整个代码,因为我认为找到这个bug会更容易。感谢。
<html>
<body>
<script>
var table1 = ["1","2","1","2"];
var rightMoves = 0;
var wrongMoves = 0;
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function printButtons(table1){
shuffle(table1);
var buttons = 0;
var y,t,k,flag;
var mybr = document.createElement('br');
var idTable =["0","0","0","0"];
var idT = 0;
document.body.appendChild(mybr);
for(var i =0 ; i<4; i++){
y = document.createElement("button");
t = document.createTextNode(table1[i]);
for(var q =0; q<idT; q++){ // check if there is already a node with this id
if(table1[i]==idTable[q]){
k= table1[i]+"1";
y.setAttribute("id",k);
flag="true";
}
else{
flag="false";
}
}
if(flag =="false"){
y.setAttribute("id",table1[i]);
}
idTable[idT]=table1[i];
idT=idT + 1;
y.appendChild(t);
document.body.appendChild(y);
buttons=buttons+1;
if (buttons == 2) {
buttons = 0;
document.body.appendChild(document.createElement('br'));
}
}
//menei na kalesw thn oncl1 gia to ka8e idtable
var ob = document.getElementById(idTable[0]);
var ob1 = document.getElementById(idTable[1]);
var ob2 = document.getElementById(idTable[2]);
var ob3 = document.getElementById(idTable[3]);
/*ob.onclick(onCl1(idTable[0],idTable));
ob1.onclick(onCl1(idTable[1],idTable));
ob2.onclick(onCl1(idTable[2],idTable));
ob3.onclick(onCl1(idTable[3],idTable)); */
//The problem is here
ob.addEventListener("click",onCl1(idTable[0],idTable));
}
function onCl1(id1,idTable){
var obj1 = document.getElementById(id1);
obj1.disabled=true;
var obj2,v,obj3,obj4;
v=0;
var temp = ["0","0","0"];
for(var i =0 ; i<4 ; i++){
if( id1 != idTable[i]){
temp[v] = idTable[i];
v=v+1;
}
}
obj2=document.getElementById(temp[0]);
obj2.onclick(onCl2(id1,temp[0]));
obj3=document.getElementById(temp[1]);
obj3.onclick(onCl2(id1,temp[1]));
obj4=document.getElementById(temp[2]);
obj4.onclick(onCl2(id1,temp[2]));
}
function onCl2(id1,id2){
alert("fail");
}
</script>
<div id="div1">
<button type="button" onclick="printButtons(table1)">play</button>
<br>
</div>
</body>
</html>
答案 0 :(得分:1)
这是因为您在尝试添加事件侦听器时调用了事件处理函数而不是传递函数。
ob.addEventListener("click", function() { onCl1(idTable[0],idTable); });
无论何时编写functionName( argument, argument, ... )
,都会在代码中的该点调用该函数。你的代码中发生了什么;调用addEventListener()
没有神奇的规则。因此,您必须使用您的参数在另一个函数中包装函数调用,并将该函数作为第二个参数传递。