单击按钮后如何获取数组的下一项?
How can I get the next items of an array after clicking on a button?
我怎样才能增加
var i = 0
每次我点击
<div onClick="my()">
,因此仅显示数组的下一项并在最后一项之后重新启动它?
<div onClick="my()" class="text">
<p id="next-p"> Next</p>
function my() {
var i = 0;
var names = [str1, str2, str3, str4, str5];
console.log(names[i]);
}
- 将
i
存储在函数范围之外,这样就不会在您每次调用该函数时都将其重新声明为 0
。
- 在函数中增加
i
。
- 您还会很快发现,只要超出数组的长度,您就需要重置
i
,因此请向函数中添加一个条件来检查这一点。
var i = 0;
var names = ['str1', 'str2', 'str3', 'str4', 'str5'];
function my() {
console.log(names[i++]);
if (i === names.length) {
i = 0;
}
}
<div onClick="my()" class="text">
<p id="next-p"> Next</p>
</div>
您必须在递增它的函数范围之外设置您想要递增的变量。
let counter = 0;
const names = ['John', 'Marie', 'James', 'Jim', 'Joe', 'Jack', 'Donald']
function increment() {
counter++;
// You should check whether the counter/index is out of bounds before accessing
document.getElementById("counter").innerHTML = names[counter] || 'Out of bounds';
}
<button onClick="increment()">Increment</button>
<div id="counter">John</div>
使用您当前设置的代码,每次调用函数时 i
变量都会重置为 0
,因此它始终具有相同的值。
编辑:谨防超出该解决方案的范围:在执行任何数组访问操作之前,您应该始终检查 counter/index 的值以避免此类错误。
我怎样才能增加
var i = 0
每次我点击
<div onClick="my()">
,因此仅显示数组的下一项并在最后一项之后重新启动它?
<div onClick="my()" class="text">
<p id="next-p"> Next</p>
function my() {
var i = 0;
var names = [str1, str2, str3, str4, str5];
console.log(names[i]);
}
- 将
i
存储在函数范围之外,这样就不会在您每次调用该函数时都将其重新声明为0
。 - 在函数中增加
i
。 - 您还会很快发现,只要超出数组的长度,您就需要重置
i
,因此请向函数中添加一个条件来检查这一点。
var i = 0;
var names = ['str1', 'str2', 'str3', 'str4', 'str5'];
function my() {
console.log(names[i++]);
if (i === names.length) {
i = 0;
}
}
<div onClick="my()" class="text">
<p id="next-p"> Next</p>
</div>
您必须在递增它的函数范围之外设置您想要递增的变量。
let counter = 0;
const names = ['John', 'Marie', 'James', 'Jim', 'Joe', 'Jack', 'Donald']
function increment() {
counter++;
// You should check whether the counter/index is out of bounds before accessing
document.getElementById("counter").innerHTML = names[counter] || 'Out of bounds';
}
<button onClick="increment()">Increment</button>
<div id="counter">John</div>
使用您当前设置的代码,每次调用函数时 i
变量都会重置为 0
,因此它始终具有相同的值。
编辑:谨防超出该解决方案的范围:在执行任何数组访问操作之前,您应该始终检查 counter/index 的值以避免此类错误。