Say you have an array var arr = ['foo', 'bar', 'baz'];.
If you want to dynamically select elements from this array, you will need a new variable. Let me name it iand give it a default value.var i = 0;
Still arr[i]; // "foo" (i === 0)
Next and previous
, , i. , , i ( ) arr.length.
function nextItem() {
i = i + 1;
i = i % arr.length;
return arr[i];
}
, , , , , i
function prevItem() {
if (i === 0) {
i = arr.length;
}
i = i - 1;
return arr[i];
}
nextItem(); // "bar" (i === 1)
prevItem(); // "foo" (i === 0 as we did `0 + 1 - 1`)
// also
prevItem(); // "baz" (decreased on 0)
nextItem(); // "foo" (increased at end of arr)
, .
DOM
, document.write . , id DOM JavaScript .
<div id="output"></div>
<div>
<span id="prev_button">Previous</span>
<span id="next_button">Next!</span>
</div>
, <div> JavaScript document.getElementById('output'), <span>.
<div>,
document.getElementById('output').textContent = arr[0]; // initial value
// if i is still at it default value, we could have used i instead of 0
<span>, . <div> , .
document.getElementById('prev_button').addEventListener(
'click',
function (e) {
document.getElementById('output').textContent = prevItem();
}
);
document.getElementById('next_button').addEventListener(
'click',
function (e) {
document.getElementById('output').textContent = nextItem();
}
);
! , " ". : <script> , , , ..
window.addEventListener('load', function () {
});
DEMO
JavaScript, . - IIFE " " , .