我有一个使用JavaScript生成的数独表。生成表后,我还为每个单元格附加了一个数字输入字段和一个函数。目前,该函数仅传入最后生成的单元格id(例如R9C9),而不是最近修改过的单元格。我宁愿让函数get传递给用户修改的当前单元格id,这样我就可以检查行,列和当前正方形是否存在冲突而不是板上的每个单元格。我正在尝试不使用jQuery,但任何帮助都会受到赞赏。
这是附加数字字段的代码,以及函数。我相信它目前附加的功能是匿名的,只要我能将附加的匿名函数与当前单元格相关联就无所谓了。
for (i = 1; i <=9; i++)
{
for (j = 1; j <= 9; j++) {
temp = document.getElementById('R'+i+'C'+j);
if (temp.innerHTML == "")
{
var temp2 = temp.appendChild(document.createElement("input"));
temp2.type = "number";
temp3 = document.getElement('R'+i+'C'+j);
temp2.onkeyup = function(){conflictChecker(temp3)};
}
}
}
这是生成表格的代码。 函数makeGrid(x,y,name){
var tableDiv = document.getElementById("gameTable");
var table = document.createElement('table');
table.id = "theTable";
table.style.width = '100px';
table.style.border = 'thick solid black';
for (var i = 1; i <= x; i++) {
var row = table.insertRow();
row.id = "Row" + i;
for (var j = 1; j <= y; j++) {
var cell = row.insertCell();
cell.id = "R" + i + "C" + j;
cell.classList.add();
cell.style.border = '1px solid';
if((i%3) == 0)
{
cell.style.borderBottom = "thick solid black";
}
if(((j-1)%3) == 0)
{
cell.style.borderLeft = "thick solid black";
}
}
}
tableDiv.appendChild(table)
我添加的表格的原始元素,因此用户无法修改它们。
document.getElementById("R_C_").innerHTML = "someNumber";
我尝试通过添加此
来从函数中分配函数for (i =1; i <= 9; i++) {
for (j = 1; j <= 9; j++) {
temp = document.getElementById('R' + i + 'C' + j);
temp.onkeyup = function(){conflictChecker(temp)};
}
}
任何帮助都会非常感激。我尝试了几种不同类型的语法,但它们似乎没有用。
答案 0 :(得分:1)
正在发生的事情是javascript不计算temp3的值 - 它在调用函数之前将其保持为变量,然后计算值,该值将等于最后一次迭代时的值。 ..
你试过这个吗?
temp2.onkeyup = function(){conflictChecker(this.parent)};
答案 1 :(得分:0)
我解决了我的问题。出于某种原因,使用onkeyup函数为我的事件无效。我将它切换到onchange()并通过传入'this'
来获取当前单元格for (i = 1; i <=9; i++)
{
for (j = 1; j <= 9; j++) {
temp = document.getElementById('R'+i+'C'+j);
if (temp.innerHTML == "")
{
var temp2 = temp.appendChild(document.createElement("input"));
temp2.type = "number";
temp2.id = 'R'+i+'C'+j+'2';
temp2.onchange = function(){conflictChecker(this)};
}
else
{
theVal = temp.innerHTML;
temp.value = theVal;
temp.id = 'R'+i+'C'+j+'2';
}
}
}
我也分配了不同的Id,以便我可以从conflictChecker中查找单元格的值。可能不是最优雅的解决方案,但它有效。