想要javascript循环

时间:2014-02-18 22:08:06

标签: javascript

我在html表的主行下面添加了子行,具体取决于按下哪个主行按钮。以下是一些代码:

if (document.getElementById("hdnSub0")) {
    roz0 = document.getElementById("hdnSub0").value || 0;
}
    ...
if (document.getElementById("hdnSub10")) {
    roz10 = document.getElementById("hdnSub10").value || 0;
}
nroz0 = parseInt(roz0, 10);
    ...
nroz10 = parseInt(roz10, 10);
if (intMainRow == 0) {
    i = nroz0 + 2
};
    ...
if (intMainRow == 10) {
    i = nroz0 + 2 + nroz1 + 1 + nroz2 + 1 + nroz3 + 1 + nroz4 + 1 + nroz5 + 1 + nroz6 + 1 + nroz7 + 1 + nroz8 + 1 + nroz9 + 1 + nroz10 + 1
};
row = table.insertRow(i); 

我想为if(intMainRow ...)编写一个循环,但我还是没能弄明白。

1 个答案:

答案 0 :(得分:2)

所以使用循环!

考虑getElementById("hdbSub" + i),其中i是从0..10递增的循环变量。然后,您可以使用循环(或中间数组)转到0..x,具体取决于intMainRow的值。

例如:

// Because nroz0 + 2, but nrozOther + 1
// (You could also encode with an if/condition in the loop, but I
//  feel like showing it this way.)
var incrs = [2,1,1,1,1,1,1,1,1,1,1];

// Running total (I use i/j/k only for loops.)
var total = 0;

// Will loop [0, intMainRow], an inclusive range, because of "<=".
// We loop once for each "field" and add the result in total.
for (var i = 0; i <= intMainRow; i++) {
   var elm = document.getElementById("hdnSub" + i);
   if (elm) {
     // Add the value to the total along with
     // the increment (+2/+1) for this index.
     // (Each loop "adds" the next value to the equation
     //  written manually in the the original code.)
     var v = parseInt(elm.value, 10) || 0;
     total += v + incrs[i];
   }
}

row = table.insertRow(total);