2014-04-14 39 views
0
<div id="history"> 
     <div id="histheading" class="pull-left">History</div> 
     <div id='hist'><canvas id="test"></canvas></div> 
</div> 


var left=100; 
var t=-150; 
function doHistory_double() 
    { 
     var data = localStorage.getItem('HTML5TTT'); 
     data = JSON.parse(data); 
      data.reverse(); 
     var container = document.getElementById('hist'); 
     // Clear the container 
     while (container.hasChildNodes()) 
     { 

      container.removeChild(container.firstChild); 
     } 
     // Loop through the data 
     canvID = 0; 
     for(x in data) 
     { 
      var i=1; 
      var hist = data[x]; 
      if(hist.datetime == undefined) 
       break; 
      var elem = document.createElement('div'); 

      elem.style.marginLeft=lef + "px"; 
      if(i==1){ 
      elem.style.marginTop=t + "px"; 
      } 
      else 
      elem.style.marginTop="0px"; 
      i++; 
      elem.innerHTML = "<p><strong>"+hist.datetime+"</strong><br>Winner: "+hist.winner+"<br><canvas id='can"+canvID+"' width='100px' height='100px' ></canvas>"; 
      container.appendChild(elem); 
      drawMiniBoard_double(document.getElementById("can"+canvID),hist.board); 
      canvID++; 
      lef+=310; 

     } 


    } 

這是我的javscript代碼。 hist是一個顯示遊戲歷史的div。我收到錯誤,因爲無法調用方法'hasChildNodes'爲null。我在做了一些使用左側變量並且t margin-top和margin-left之後出現此錯誤。幫我解決這個問題。容器hasChildNodes()顯示空值。爲什麼

+0

這意味着'container'是'null',即在您調用函數的那一刻,ID爲'hist'的元素不存在。由於您發佈的內容不是完整的示例,因此很難提供具體的解決方案。請參閱[爲什麼jQuery或諸如'getElementById'的DOM方法未找到該元素?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such- as-getelementbyid-not-the-element)的一般建議。 –

回答

0

將其寫入一個函數並將其稱爲onload文件。

function deleteChildren() { 
    var container = document.getElementById('hist'); 
    // Clear the container 
    while (container.hasChildNodes()) 
    { 
     container.removeChild(container.firstChild); 
    } 
} 


<body onload="deleteChildren()"> 
    <div id="history"> 
     <div id="histheading" class="pull-left">History</div> 
     <div id='hist'><canvas id="test"></canvas></div> 
    </div> 
</body> 
0

其工作完美..檢查fiddle

我已經綁定點擊方法然後調用你的代碼,並提供警報,顯示無論是我們得到的容器或內部沒有一個孩子..

--HTML--

<div id="history"> 
     <div id="histheading" class="pull-left">History</div> 
     <div id='hist' onclick=f()><canvas id="test"></canvas></div> 
</div> 

- JS -

function f() 
{  
     var container = document.getElementById('hist'); 
    // Clear the container 
     alert(container.hasChildNodes()); 
    while (container.hasChildNodes()) 
    { 
     container.removeChild(container.firstChild); 
    } 
} 

http://jsfiddle.net/FLC3R/

+0

實際上容器有孩子,它對於haschildnodes()返回true。但我收到錯誤「無法調用方法'hasChildNodes'」。如何清除錯誤。 ?謝謝 – Jack

+0

看到你接受了它的返回真正的意思是它的調用方法,那麼只有它會返回TRUE/FALSE ..然後最新的問題,在哪個線路出現錯誤。 –

+0

我在這條線上收到錯誤,while(container.hasChildNodes()) – Jack