JS For for condition with conditionals

时间:2013-10-23 02:48:13

标签: javascript

我有一个带有For循环的函数,它将从0计数到n的值,但是,当它达到5或7的倍数时,将包含一个字符串而不是整数。问题是它只显示1个输出,我希望它列出每次迭代附加输出。 (1
,2
,3
,4
,等)。

HTML:

<button onclick="callit()">Call OneTwo</button>
<div id="OneTwo">Test</div>

JS:

            function callit() {
                x = 0;
                n = 100;
                z = "The number is " + x + "<br>";
                one = "One";
                two = "Two";
                ot = one + " " + two;
                obj = document.getElementById('OneTwo');

                for (x; x <= n; x++) {
                    if ((x % 5) === 0) {
                        z = one;
                    }
                    if ((x % 7) === 0) {
                        z = two;
                    }
                    if (((x % 3) === 0) && ((x % 5) === 0)) {
                        z = ot;
                    }
                    obj.innerHTML = z;
                }
            }

3 个答案:

答案 0 :(得分:2)

在这里,你应该做你想要的:

obj.innerHTML = obj.innerHTML + "<br />" + z;

您需要维护innerHTML的值而不是替换它。

答案 1 :(得分:1)

嗯,你用当前值替换整个div的html。你需要追加它。请尝试以下方法:

obj.innerHTML = obj.innerHTML + '<br/>' + z;

jsfiddle

答案 2 :(得分:0)

您需要获取之前的值并附加新值。你刚刚附加现有的,这就产生了问题。

<!DOCTYPE html>
<html>
<head>
<script>
function callit() {
                x = 0;
                n = 100;
                z = "The number is " + x + "<br>";
                one = "One";
                two = "Two";
                ot = one + " " + two;
                obj = document.getElementById('OneTwo');

                for (x; x <= n; x++) {
                    if ((x % 5) === 0) {
                        z = one;
                    }
                    if ((x % 7) === 0) {
                        z = two;
                    }
                    if (((x % 3) === 0) && ((x % 5) === 0)) {
                        z = ot;
                    }
                   obj.innerHTML = obj.innerHTML + "<br />" + z;
                }
            }
</script>
</head>
<body>

<button onclick="callit()">Call OneTwo</button>
<div id="OneTwo">Test</div>

</body>
</html>