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

Javascript 通过getElementByID将脚本应用于多个ID,javascript,charts,progress-bar,Javascript,Charts,Progress Bar,我正在尝试创建多个ID的条形图/进度条。但出于某种原因,我被难住了 var bar = document.getElementById("chart1", "chart2", "chart3"); var progress = document.getElementById("progress1", "progress2", "progress3").innerHTML; function setProgress(percent){

我正在尝试创建多个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);
任何帮助都会很棒。

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

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

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);
}

您需要使用数组并在函数中迭代它,如下所示

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

for(var i=0;i<bar.length;i++)
{
  var barElement = document.getElementById(bar[i]);
  // do your task with barElement
}
var-bar=[“图表1”、“图表2”、“图表3”];

for(var i=0;i
getElementById
只接受一个参数。我理解。有没有办法通过创建数组并应用它来解决这个问题?这就是你的方法。有了这个,你对var进度也会这样做吗?@Joey Kirk很好,如果你觉得它解决了你的问题的话。