[英]Javascript: How to display next array value on button click
I am trying to write a code in javascript/jquery and html which I thought would be fairly simple, but turns out to be quite challenging (to me). 我试图用javascript / jquery和html编写一个代码,我认为这很简单,但是对我来说却是相当具有挑战性的。 I have a program which computes the first x numbers of the fibonacci sequence, and stores it in an array.
我有一个程序可以计算斐波那契数列的前x个数字,并将其存储在数组中。 What I am trying to do is make two buttons that will display the next or previous number in the sequence.
我正在尝试做的是使两个按钮显示顺序中的下一个或上一个数字。 This is what I have so far.
到目前为止,这就是我所拥有的。
Javascript: Javascript:
var all = new Array();
fib = function (numMax) {
for (i = 0, j = 1, k = 0; k < numMax; i = j, j = x, k++) {
x = i + j;
//window.document.write(x + " ");
all[k] = x;
}
};
fib(1000);
fibon = function () {
getElementById("mynum").innerHTML = "all[+1]";
};
HTML: HTML:
<input type="text" id="mynum">
<button onclick="fibon();">Next</button>
You need a variable that contains the current index, and then increment it each time you click. 您需要一个包含当前索引的变量,然后在每次单击时将其递增。
fibindex = 0;
function fibon() {
if (fibindex >= all.count) {
document.getElementById("mynum").value = "We've run out of Fibonacci numbers";
} else {
document.getElementById("mynum").value = all[fibindex];
fibindex++;
}
}
Also, notice that you should not put quotes around a use of a variable. 另外,请注意,您不应在使用变量时引号。 Add you use
.value
to fill in an input, not .innerHTML
. 添加您使用
.value
填写输入,而不是.innerHTML
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.