0

我正在尝试为多个 ID 创建条形图/进度条。但由于某种原因,我被难住了。

        var bar = document.getElementById("chart1", "chart2", "chart3");
        var progress = document.getElementById("progress1", "progress2", "progress3").innerHTML;
        function setProgress(percent){
            bar.style.width = percent + "%";

            if (percent > 70)
                bar.className = "graph graph-green";
            else if (percent > 40)
                bar.className = "graph graph-yellow";
            else if (percent > 0)
                bar.className = "graph graph-red";
        }

        var interval = setInterval(
            function(){
                setProgress(progress);
            }, 100);

任何帮助都是极好的。

4

2 回答 2

1

就像 Blender 说的,getElementById只接受一个参数,并返回一个元素。

您可以将该功能提取到一个函数中:

function applybar(bar,progressElem) {
    var progress = progressElem.innerHTML;

    function setProgress(percent) {
        bar.style.width = percent + "%";

        if (percent > 70) bar.className = "graph graph-green";
        else if (percent > 40) bar.className = "graph graph-yellow";
        else if (percent > 0) bar.className = "graph graph-red";
    }

    var interval = setInterval(function () {
        setProgress(progress);
    }, 100);

}

然后用法将类似于

applybar(document.getElementById("chart1"),document.getElementById("progress1"));
applybar(document.getElementById("chart2"),document.getElementById("progress2"));
applybar(document.getElementById("chart3"),document.getElementById("progress3"));

一些清理:

var interval = setInterval(function () {
     setProgress(progress);
}, 100);

可以改写为setInterval(setProgress,100,progress),不止于此。间隔长度可以作为参数传递。

让我们给它取别名var $ = document.getElementById并将其放入一个数组中:

var bars = [{bar:$("chart1"),progress:$("progress1")},
           {bar:$("chart2"),progress:$("progress2")},
           {bar:$("chart3"),progress:$("progress3")}];

然后使用它

bars.forEach(function(bar){ //forEach requires a modern browser
    applybar(bar.bar,bar.progress);
}
于 2013-06-11T17:04:04.907 回答
0

您需要使用数组并通过您的函数对其进行迭代,如下所示

var bar =["chart1", "chart2", "chart3"];

for(var i=0;i<bar.length;i++)
{
  var barElement = document.getElementById(bar[i]);
  // do your task with barElement
}
于 2013-06-11T17:06:22.023 回答