Gather div class into a javascript array
My current html looks like this:
<div class="wrapper" style="display:block;" id="item0"><!--- Stuff --></div>
<div class="wrapper" style="display:none;" id="item1"><!--- Stuff --></div>
<div class="wrapper" style="display:none;" id="item2"><!--- Stuff --></div>
<div class="wrapper" style="display:none;" id="item3"><!--- Stuff --></div>
<div class="wrapper" style="display:none;" id="item4"><!--- Stuff --></div>
And then I have a back/forward link which call the corresponding javascript function, it looks like this:
function switchNextItem() {
var element0 = document.getElementById('item0');
var element1 = document.getElementById('item1');
var element2 = document.getElementById('item2');
var element3 = document.getElementById('item3');
var element4 = document.getElementById('item4');
if (element0.style.display == 'block') {
element0.style.display = 'none';
element1.style.display = 'block';
} else if (element1.style.display == 'block') {
element1.style.display = 'none';
element2.style.display = 'block';
} else if (element2.style.display == 'block') {
element2.style.display = 'none';
element3.style.disp开发者_StackOverflow社区lay = 'block';
} else if (element3.style.display == 'block') {
element3.style.display = 'none';
element4.style.display = 'block';
} else if (element4.style.display == 'block') {
element4.style.display = 'none';
element0.style.display = 'block';
}
}
Are there any possibilities for me to make this more dynamically?
Thanks! (I'm not familiar with javascript).
You'd love jQuery: http://jsfiddle.net/TCQum/.
function switchNextItem() {
$('div.wrapper:visible') .hide() .next() .show();
// select visible div | hide it | goto next | show that one
}
Edit: A more precise one:
function switchNextItem() {
var next = $('div.wrapper:visible:eq(0)')
.hide()
.next('div.wrapper'); // next one will be stored in next
if(next.length === 0) { // if there is no next one, show first one agan
$('div.wrapper:eq(0)').show();
} else { // otherwise show next one
next.show();
}
}
And with .prev
:
function switchNextItem() {
var prev = $('div.wrapper:visible:eq(0)')
.hide()
.prev('div.wrapper'); // prev one will be stored in prev
if(prev.length === 0) { // if there is no prev one, show last one
$('div.wrapper:last').show();
} else { // otherwise show prev one
prev.show();
}
}
Something like this should work.
function switchNextItem() {
var items=['item0','item1','item2','item3','item4'];
for(var i=0;i<items.length;i++){
var element = document.getElementById(items[i]);
if (element.style.display == 'block') {
element.style.display = 'none';
var nextElement = document.getElementById(items[(i+1) % items.length]);
nextElement.style.display = 'block';
break;
}
}
}
精彩评论