2012-09-10 39 views
0

當我點擊元素時,它會啓動,但是當再次點擊時它不會做任何事情。刷新頁面並再次點擊工作(直到再次點擊)。爲什麼?爲什麼DIV由`outerHTML`改變仍然沒有響應

當div被點擊時,AJAX將它傳遞給PHP xmlhttp.send();; 「點擊」事件由document.getElementById('b_'+countr).addEventListener("click", selectionMade);處理。

我認爲這是與文件加載有關 - 我想發射一些由outerHTML更改的東西;完整的代碼提供如下:

// prepare clicable map 
for (x = 1; x <= 16; x++) { 
for (y = 1; y <= 16; y++) { 
    (function prepareClickableMap() { 
     var cords = x + "x" + y; 
     var el = document.getElementById(cords); 
     el.addEventListener("click", function (e) { B_modeWindow('1', cords) }); 
    })(); 
} 
} 

//passing selection 
for (countr = 1; countr <= 256; countr++) { 
    document.getElementById('b_'+countr).addEventListener("click", selectionMade); 
} 


var s; 
function selectionMade(e) { 
    selection = e.currentTarget.id.split("_"); 
    s = selection[1]; 
} 

// pass edited map info 
function B_modeWindow (id,XxY) { 
    if (s !== undefined) {  
     loading(); 

     var xmlhttp; 
     var position = XxY; 

     if (window.XMLHttpRequest) { 
      xmlhttp=new XMLHttpRequest(); 
     } else { 
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
     } 

     var xy = position.split("x"); 

     xmlhttp.onreadystatechange=function() { 
      if (xmlhttp.readyState==4 && xmlhttp.status==200) { 
       document.getElementById(XxY).outerHTML=xmlhttp.responseText; 

       hideloading(); 
      } 
     } 

     xmlhttp.open("GET","processMapEdit.php?id="+id+"&x="+xy[0]+"&y="+xy[1]+"&s="+s,true); 
     xmlhttp.send(); 
    } 
} 

回答

0

innerHTMLouterHTML徹底摧毀一切正在改變,並用新的HTML替換它。特別是這意味着任何事件監聽器都會被銷燬,所以您必須要麼不使用innerHTML/outerHTML,要麼在之後重新應用監聽器。

旁註:不要將事件偵聽器附加到地圖上的每個圖塊,而是將其附加到地圖本身,並使用event.target來查找單擊了哪個圖塊。

+0

如何重新應用聽衆? +它有點慢? –

+0

設置'outerHTML'後,添加代碼以附加事件偵聽器。 –

相關問題