我有20个元素的数组。我想在单击按钮时显示前五个元素,然后在单击另一个按钮时显示下五个元素,依此类推。如果您能帮助我编写代码,我将不胜感激。
var words = [20];
var newArray = words.slice(0, 5);
var words = ["day", "white", "go", "low", "wise", "up", "sit", "now",
"good", "grapes", "banana",
"mango", "orange", "pears", "melon", "guava", "sunflower", "marigold",
"jasmine", "sunflower"];
var x = "";
var count = 0;
function nextElems() {
if (count < words.length) {
var newArray = words.slice(0, 5);
x += '<div>' + newArray + '</div>';
document.getElementById('yes').innerHTML = x;
count = newArray;
} else {
count = 0;
var secondArray = words.slice(5, 10);
x += '<div>' + secondArray + '</div>';
document.getElementById('yes').innerHTML = x;
}
x = "";
}
<button onclick="nextElems();"> Try </button>
<div id="yes"> </div>
我尝试过的内容正确显示了两次结果,但第三次没有显示。
答案 0 :(得分:1)
这可以解决问题。您需要将count变量用作slice方法的参数:
var words = ["day", "white", "go", "low", "wise", "up", "sit", "now",
"good", "grapes", "banana",
"mango", "orange", "pears", "melon", "guava", "sunflower", "marigold",
"jasmine", "sunflower"
];
var count = 0;
function nextElems() {
var newArray = words.slice(count, count + 5);
var x = document.createElement("div");
x.innerHTML = newArray;
document.getElementById('yes').appendChild(x);
count += 5;
}
<body>
<button onclick="nextElems();"> Try </button>
<div id="yes"> </div>
</body>
答案 1 :(得分:0)
使用words.slice(0, 5);
代替words.slice(count, count + 5);
而不是将count
设置为0
,而是增加它:count += newArray.length;
var words = ["day", "white", "go", "low", "wise", "up", "sit", "now",
"good", "grapes", "banana",
"mango", "orange", "pears", "melon", "guava", "sunflower", "marigold",
"jasmine", "sunflower"
];
var x = "";
var count = 0;
function nextElems() {
if (count < words.length) {
var newArray = words.slice(count, count + 5);
x += '<div>' + newArray + '</div>';
document.getElementById('yes').innerHTML = x;
count += newArray.length;
} else {
count = 0;
var secondArray = words.slice(count, count+5);
x += '<div>' + secondArray + '</div>';
document.getElementById('yes').innerHTML = x;
count += 5;
}
x = "";
}
<button onclick="nextElems()">Click</button>
<div id="yes"></div>