2012-10-21 49 views
0

我已经使用cloneNode来保存和恢复数独表。但是,当我克隆它并恢复表时,恢复的版本不再可编辑。javascript克隆节点重新附加事件侦听器

//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(); 
    } 

这是我的附加事件处理程序,但是当我以同样的方式重新安装我仍然有同样的问题

+0

试试这个:http://sivavaka.blogspot.com/2010/11/javascript-clonenode-doesnt-copy-event.html –

+0

这取决于你是如何附加事件。为什么不像你最初那样重新贴上它们? – Jay

+0

不知道为什么没有发生在我身上。谢谢 – user1711576

回答

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(); 
} 

只需重新插入此代码到resotre功能重新附加事件听众