我有点迷失为什么这段代码没有显示任何东西,它曾经工作,当我没有按钮的包装函数,我在脚本中手动输入factorialize函数的参数,什么我做错了吗?
HTML
<div class="factorializing">
<h1> Factorialize a number </h1>
<input type ="text" id ="number"/>
<button id="factButton"> Factorialize</button>
<h1 id="factorialized"> </h1>
</div>
的Javascript
document.getElementById("factButton").addEventListener("click", function(){
function factorialize() {
var input = document.getElementById("number").value;
var output = document.getElementById("factorialized");
if (input === 0) {
return output.innerHTML = 1;
}
else {
return output.innerHTML = input * factorialize(input - 1) ;
}
}
});
答案 0 :(得分:1)
我认为您正在寻找类似的东西: -
document.getElementById("factButton").addEventListener("click", function() {
var input = document.getElementById("number").value;
var output = document.getElementById("factorialized");
function factorialize(input) {
if (input === 0) {
return 1;
} else {
return input * factorialize(input - 1);
}
}
output.innerHTML = factorialize(input);
});
<div class="factorializing">
<h1> Factorialize a number </h1>
<input type="text" id="number" />
<button id="factButton">Factorialize</button>
<h1 id="factorialized"> </h1>
</div>
这将以递归方式调用您的factorialize
函数并设置输出。
答案 1 :(得分:0)
document.getElementById("factButton").addEventListener("click", function() {
var input = parseInt(document.getElementById("number").value, 10);
document.getElementById("factorialized").innerHTML = factorialize(input);
});
function factorialize(n) {
return (n <= 0) ? 1 : n * factorialize(n - 1);
}
<div class="factorializing">
<h1> Factorialize a number </h1>
<input type="text" id="number" />
<button id="factButton">Factorialize</button>
<h1 id="factorialized"> </h1>
</div>
答案 2 :(得分:0)
我只是在每次递归调用时将值写入输出,同时更改值。
document.getElementById("factButton").addEventListener("click", function() {
var input = document.getElementById("number").value;
var output = document.getElementById("factorialized");
output.innerHTML = ''
factorialize(Number(input))
function factorialize(input) {
return output.innerHTML += '' + ((input === 0)
? 1
: (input * factorialize(input - 1)))
}
});
&#13;
<div class="factorializing">
<h1> Factorialize a number </h1>
<input type="text" id="number" />
<button id="factButton">Factorialize</button>
<h1 id="factorialized"> </h1>
</div>
&#13;