Javascript只运行一次

时间:2016-06-25 10:06:49

标签: javascript

HTML

<p>What factorial would you want to calculate?</p>
<input id="factorium" type="number">
<input id="submission" type="submit" value="Calculate">

的Javascript

function factorial(x) {
    if (x === 0) {
        return 1;
    }
    return x * factorial(x - 1);
}

    var inputBox = document.getElementById('factorium').value;
    var submission = document.getElementById('submission');
    submission.onclick = function(){console.log(factorial(inputBox))};
  

已编辑 -

提交按钮只能运行一次,我需要刷新页面才能再次使用,任何想法如何修复?

3 个答案:

答案 0 :(得分:4)

您的JavaScript代码可以缩减为一行:

name: sugar
quantity: 100

这足以触发错误。问题是 void MyTransaction() { system("cls"); string mycode,line; cout << "Input code : "; cin >> mycode; ifstream newstream; newstream.open("mydatabase.txt",ifstream::in); size_t pos; while (newstream.good()){ getline(newstream,line); pos=line.find(mycode); if(pos!=string::npos) // string::npos is returned if string is not found { cout <<line; break; } } newstream.close(); } ,而应该是document.getElementById('factorium').value(); 。正如错误消息所示,.value()不是函数,无法调用。

答案 1 :(得分:0)

我创建了一个新函数,它只执行上面的代码,如下所示:

function getVals(){

    var inputBox = document.getElementById('factorium').value;
    var submission = document.getElementById('submission');
    console.log(factorial(inputBox));
}

并在输入提交按钮上添加了:

<input id="submission" type="submit" value="Calculate" onclick="getVals()">

答案 2 :(得分:0)

JS Fiddle Link

<p>What factorial would you want to calculate?</p>
<input id="factorium" type="number">
<input id="submission" type="submit" value="Calculate" onclick="calcFactorial()">

<script>

    function factorial(x) {
        if (x === 0) {
            return 1;
        }
        return x * factorial(x - 1);
    }

        function calcFactorial(){
            var inputBox = document.getElementById('factorium').value;
            var submission = document.getElementById('submission');
            console.log(factorial(inputBox));
        }
</script>