2014-04-14 30 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