<script>
function loop()
{
var input = document.getElementById('id').value;
//var ans;
for (var x = 1; x < input; x++)
{
var ans = document.getElementById('hello').innerHTML;
}
}
</script>
<input type="text" id="id" />
<input type="submit" onclick="loop()" value="isubmit">
<div id="hello"></div>
我需要在文本字段中输入数字然后提交它,然后它将显示循环。出于某种原因,我只得到白屏。它什么都不做。
答案 0 :(得分:0)
如果您想要做的是从1到输入的数字减去1,那么您可以将您的功能修改为:
function loop() {
var input = document.getElementById('id').value;
var result = document.getElementById('hello');
for (var x = 1; x < input; x++) {
result.innerHTML += x + ' ';
}
}
检查这个小提琴,看看它的实际效果:http://jsfiddle.net/arnellebalane/1ysut9L3/
答案 1 :(得分:0)
HTML
<input type = "text" id = "input_id" />
<input type = "submit" id = "submit_btn" value = "isubmit">
<div id = "hello">
...
</div>
的JavaScript
function LoopOnClickEvent(input_id, button_id, result_id)
{
input = document.getElementById(input_id);
button = document.getElementById(button_id);
result = document.getElementById(result_id);
button.onclick = function()
{
var val = parseInt(input.value);
if(Number.isNaN(val) || val < 2)
{
var old = result.innerHTML;
result.innerHTML = "Please type a real number greater than 1";
setTimeout(function(){ result.innerHTML = old; }, 1500);
}
else
{
var final_val = "";
for(var cpt = 1; cpt < val; ++cpt)
{
final_val += cpt;
}
result.innerHTML = final_val;
}
};
}
/* Exemple */
LoopOnClickEvent("input_id", "submit_btn", "hello");
我希望它会对你有所帮助:)。