我想在javascript中使用for循环获取奇数,但我想用用户输入终止循环,我不能这样做,你能帮我朋友。
我希望“x< 7”成为“x< input”
<html>
<head>
<body>
<input id="numbers" type="number">
<button onclick="odd()">Odd Numbers</button>
<p id="demo"></p>
<script>
function odd() {
var text = " ";
var x;
for ( x = 1; x < 7; x+= 2) {
text += x + " ";
}
document.getElementById("demo").innerHTML =+ text;
}
</script>
</body>
</head>
</html>
答案 0 :(得分:0)
现在您已告诉我们您想要的内容,这是我的更新代码:
基本上它只是设置一个限制并随着div的变化而改变它
<html>
<head>
<body>
<input id="numbers" type="number" onChange="change()">
<button onclick="odd()">Odd Numbers</button>
<p id="demo"></p>
<script>
var lim=7;
function change() {
lim = document.getElementById("numbers").value;
}
function odd() {
var text = " ";
var x;
for ( x = 1; x < lim; x+=2) {
text += x + " ";
}
document.getElementById("demo").innerHTML += text;
}
</script>
</body>
</head>
</html>
您可以使用setInterval
和clearInterval
来实现此目标:
var i = 1;
var myInt = setInterval(function(){
document.getElementById("div").innerHTML += i;
i+=2;
}, 100);
<button onClick="clearInterval(myInt)">STOP</button>
<div id="div"></div>
答案 1 :(得分:0)
我认为这是你正在尝试的,这会查看你的用户输入,如果它比你的起始迭代器大,它就会循环。
const button = document.querySelector('.go');
button.addEventListener('click', e => {
const input = document.getElementById('numbers');
const output = document.getElementById('demo');
if (input.value == 0) { return; }
for (let i = 0, len = input.value; i <= len; i++) {
if (i % 2 === 1) {
output.textContent += i.toString();
}
}
});
&#13;
<html>
<head>
<body>
<input id="numbers" type="number">
<button class='go'>Odd Numbers</button>
<p id="demo"></p>
</body>
</head>
</html>
&#13;