容器hasChildNodes()显示空值。为什么

时间:2014-04-14 03:48:57

标签: javascript html dom

<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。我收到错误,因为无法调用方法&has; hasNildNodes&#39;我使用变量left和t,margin-top和margin-left做了一些事后我得到了这个错误。帮我解决这个问题。

2 个答案:

答案 0 :(得分:0)

将其写入函数并将其称为onload of document。

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>

答案 1 :(得分:0)

完美运作..查看fiddle

我已经绑定了click方法,然后调用了你提供的代码,并提醒我们是否在容器内部有一个孩子..

- 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/