document.CreateElement(div)无效...

时间:2013-12-04 18:38:06

标签: javascript html5 dom

我正在尝试在运行时创建一个div元素并在其中放置一个图表元素,这似乎不起作用。

function drawChart() {

        // Create the data table.
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Topping');
        data.addColumn('number', 'Slices');
        data.addRows([
          ['Mushrooms', 3],
          ['Onions', 1],
          ['Olives', 1],
          ['Zucchini', 1],
          ['Pepperoni', 2]
        ]);

        // Set chart options
        var options = {'title':'How Much Pizza I Ate Last Night',
                       'width':400,
                       'height':400};

        // Instantiate and draw our chart, passing in some options.
        //context.fillRect(0,0,100,100);
        div = document.createElement('div');
        div.style.position = "absolute";
        div.style.top = "0";
        div.style.left = "0";
        document.body.appendChild(div);
        var chart = new google.visualization.LineChart(document.getElementById('div'));
        chart.draw(data, options);
      }

当我在html中声明div时,它有效。我做错了吗?

2 个答案:

答案 0 :(得分:1)

您没有将div的id设置为div。看起来你应该使用:

var chart = new google.visualization.LineChart(div);

答案 1 :(得分:1)

您正在执行document.getElementById('div'),但您创建的div的ID尚未设置为div。你为什么不这样做:

var chart = new google.visualization.LineChart(div);

另一种选择是实际设置id:

div.id = "div";
...
var chart = new google.visualization.LineChart(document.getElementById('div'));