通过getElementByID将脚本应用于多个ID

时间:2013-06-11 16:59:37

标签: javascript charts progress-bar

我正在尝试在整个过程中创建多个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);

任何帮助都会很棒。

2 个答案:

答案 0 :(得分: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);
}

然后使用它

{{1}}

答案 1 :(得分: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
}