0

我有一个带有 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;
                }
            }
4

3 回答 3

2

给你,这应该做你正在寻找的:

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

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

于 2013-10-23T02:55:29.243 回答
1

好吧,您正在用当前值替换整个 div html。您需要附加它。尝试以下操作:

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

jsfiddle

于 2013-10-23T02:52:21.267 回答
0

You need to get the previous value and append with the new one. You had just append on existing one, which makes the problem.

<!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> 
于 2013-10-23T02:58:00.753 回答