我试图创建一个函数,将window.onload函数中的变量传递给另一个函数的引用。我希望window.onload中的var i在markTheSquare的函数定义中用作i的实际参数。编辑抱歉,我忘记在OP中添加此内容,但规格明确指出markTheSquare没有任何正式参数。
var boardState;
var markCount;// Global variable that stores the value of the number of marks.
var winningCombinations;
window.onload = function()
{
var i;
i = 0;
markCount = setMarkCount(0); // calls the mutator function setMarkCount to change the value of markCount to 0.
winningCombinations = "012345678036147258246048";
boardState = "012345678036147258246048";
while ( i < 9)
{
document.getElementById("box" + i).onclick = markTheSquare;
i = i + 1;
}
}
function markTheSquare() // uses the this keyword to concatenate "X" to the inner HTML of the current element.
{
this.onclick = null; // Disassociates the oncliick function with clicked()
this.innerHTML = getXorO(); // Concatenates the result of getXorO to the current innherHTML of the element.
updateBoardState(getXorO(), i);
window.alert(updateBoardState(getXorO(), i));
setMarkCount(getMarkCount() + 1) // Increment markCount by 1.
}
function updateBoardState(getXorO, squareNumber)
{
var boardState;
var loc;
var winners;
winners = getWinningCombinations();
boardState = getBoardState()
loc = winners.indexOf(squareNumber);
squareNumber = "" + squareNumber;
while(loc >= 0)
{
replaceCharacterInString(boardState, loc, getXorO);
loc = winners.indexOf(squareNumber);
}
return setBoardState(boardState);
}
答案 0 :(得分:0)
你应该让markTheSquare
生成一个闭包的工厂。像这样:
function markTheSquare(i) {
return function() {
//...
updateBoardState(getXorO(), i);
//...
}
}
您的点击处理程序的分配是:
document.getElementById("box" + i).onclick = markTheSquare(i);