0

我想知道是否有人可以帮助这个函数,它来自谷歌代码折线图,我想做的是从下面的 distanceField 变量中添加值,并希望每次有新值进入时更新图表,而不是确定我是否甚至采取了处理问题的最佳方法,但对问题的任何见解都会有所帮助 提前谢谢你。

    function drawVisualization2() {
    var d2 = document.getElementById('distanceField').value;
    var i;
    var arr = new Array();
    setInterval(function() {var f1 =document.getElementById('resultField').value;},5000);
    for (i = 0; i < 10; i++) {
    var f1 = document.getElementById('resultField').value;
    var d1 = parseInt(f1, 10);
    setTimeout(function() {
    //setInterval(function() {app.sendConnection()}, 10000);        
    //var f1 = document.getElementById('resultField').value;
    arr[i] = d1;
    }, 6000);
    }
    var data = google.visualization.arrayToDataTable([
    [ 'x', 'title' ], [ '1', arr[0] ], [ '2', arr[1] ],
    [ '3', arr[2] ], [ '4', arr[3] ], [ '5', arr[4] ],
    [ '6', arr[5] ], [ '7', arr[6] ], [ '8', arr[7] ],
    [ '9', arr[8] ], [ '10', arr[9] ],
    //['N',   1,       0.5,         1]
    ]);
    // Create and draw the visualization.
    new google.visualization.LineChart(document
    .getElementById('visualization2')).draw(data, {
    curveType : "function",
    width : 500,
    height : 350,
    vAxis : {
    maxValue : d2 / 2
    }
    });
    }
4

1 回答 1

0

您发布的代码块有很多问题,包括范围界定和同步问题 - 而不是尝试将其合并以使其工作,我重写了它并评论了我为什么这样做:

/**
 * A JS class that you can instansiate with the "new" construct 
 * on page/api load - this keeps everything self-contained and 
 * for the most part, out of the global scope.
 */
function ChartObject(){

    // internal function - neater way to grab elements
    function $(x){ return document.getElementById(x); }

    // some default data
    this.data = [['x', 'Metric Title'], ['start',0]];

    // read values from our DOM elements and add to our data array
    this.update = function(){
        var dis = $('distanceField').value.trim(),
            res = parseInt($('resultField').value, 10);
        if(!isNaN(res) && !!dis){
            this.data.push([dis, res]);
            this.draw();
        } else {
            alert('invalid entry');
        }
    };

    // redraw our graph based on our current data array
    this.draw = function(){   
        new google.visualization.LineChart($('visualization')).draw(
            google.visualization.arrayToDataTable(this.data), 
            {
                curveType : "function",
                width : 450,
                height : 300
            }
        );
    }

    // the following is executed once when the ChartObject is first called

    // draw the object with initial data
    this.draw();

    // add listener to button that user can click to "update" graph
    // this could be adapted to work with "onkeyup" rather than trying
    // to hack with "setTimeout"
    $('addRecord').onclick = function(){
        myChartObject.update();
    }

};

jsFiddle:工作示例

于 2013-08-29T12:45:26.300 回答