javascript clone node reattach事件监听器

时间:2012-10-21 15:32:48

标签: javascript clone

我使用了cloneNode来保存和恢复数独表。但是,当我克隆它然后恢复表时,恢复的版本将不再可编辑。

//Create Save Function and store in a cloneNode
function Save(){
var table = document.getElementById("sudoku");
clone = table.cloneNode(true);  
}
//Create Restore Function and restore saved state from the cloneNode and delete parent table
function Restore(){
var table = document.getElementById("sudoku"),
parent = table.parentNode;
parent.removeChild(table);
parent.appendChild(clone);
}

以下是我的事件处理程序

function selectCell() {
if (current_cell !== null) {
    current_cell.className = 'tofill';
}
current_cell = this;
current_cell.className = 'selected';
 }

// Capture keyboard key presses. If the key pressed is a digit
// then add it to the current cell. If it is a space then empty
// the current cell.
function keyPress(evt) {
if (current_cell == null)
    return;
var key;
if (evt)
    // firefox or chrome
    key = String.fromCharCode(evt.charCode);
else
    // IE
    key = String.fromCharCode(event.keyCode);
if (key == ' ')
    current_cell.innerHTML = '';
else if (key >= '1' && key <= '9')
    current_cell.innerHTML = key;
  }

如何重新附加事件侦听器,以便在保存后恢复表时,表格仍可编辑。

修改

 var current_cell = null; // the currently selected cell
 var saved = {};        // Object for saving the current game
 function initialize() {
var col, row;
// Work through all the cells in the table and set
// onclick event handlers and classNames for the empty
// ones.
for (row = 0; row <=8; row++) {
    for (col=0; col <= 8; col++) {
        var cell = document.getElementById('cell_' + col + '_' + row);
        if (!parseInt(cell.innerHTML)) {
            // cell is empty
            cell.onclick = selectCell;
            cell.className = 'tofill';
        }
    }
}
document.onkeypress = keyPress;
save();
    }

这是我附加事件处理程序的方式,但当我以同样的方式重新连接时,我仍然遇到同样的问题

1 个答案:

答案 0 :(得分:0)

var current_cell = null; // the currently selected cell
var saved = {};        // Object for saving the current game
function initialize() {
var col, row;
// Work through all the cells in the table and set
// onclick event handlers and classNames for the empty
// ones.
for (row = 0; row <=8; row++) {
for (col=0; col <= 8; col++) {
    var cell = document.getElementById('cell_' + col + '_' + row);
    if (!parseInt(cell.innerHTML)) {
        // cell is empty
        cell.onclick = selectCell;
        cell.className = 'tofill';
    }
  }
}
document.onkeypress = keyPress;
save();
}

只需将此代码插入还原功能即可重新附加事件侦听器