I have a dynamic page which has a parent div called 'divWiz' where I have to do the following:
count total div's inside 'divWiz' and hide 50% of them. For example: If I have 50 child div's inside divwiz, I want to show 25 and hide the rest.
At the end of the 25 div's, two links should appear that says 'Show Next' and 'Show All'.
If the user clicks the 'Show Next' link, the first 25 should be hidden and the next 25 visible. 'Show Next' link should be invisible now.
If the user clicks 'Show All', all the div's should be visible. Both the links will disappear once the user clicks Show All.
How can I do this? Since this involves lot开发者_高级运维 of traversing, I am looking for jquery code with performance.
Here are some hints to get you started:
$('#divWiz > div')
will get you all the DIVs within "divWiz".$(something).length
is the number of selected elements.$(something).slice(start, end)
lets you operate on a subset of selected elements.
You should be able to put these together to do what you want.
all you need to do is have onclick handlers that show/hide either firstHalf
, secondHalf
or both.
var divCount = $('#divWiz>div').length;
var firstHalf = $('#divWiz>div').slice(0,divCount/2);
var secondHalf = $('#divWiz>div').slice(divCount/2);
jQuery wont give you more performance, it will give you an easier way to implement. If you need better performance, wrap those "packs" of 25 div's into common parents and show/hide those parents(should be 25 times faster)
You can make use of the index numbers:
$('#divWiz > div:lt(25)') // all divs of index 0 to 24
$('#divWiz > div:lt(50):gt(24)') // all divs of index 25 to 49
Caution! :gt(-1)
doesn't work!
So, here's a quick and dirty full working example of something like what you're describing:
HTML:
<input value=" Next " type="button"/>
<input value=" Prev " type="button"/>
<input value=" Show All " type="button"/>
<div id="divWiz"></div>
JS:
$(function() {
var i, cutoff, total = 50;
for(i=0; i<total; ++i)
$(document.createElement("div")).html(i).appendTo("#divWiz");
cutoff = total/2;
$("#divWiz > div").hide();
$("#divWiz > div:lt("+cutoff+")").show();
$("input[value=' Next ']").click(function() {
$("#divWiz > div").hide();
$("#divWiz > div:gt("+(cutoff - 1)+")").show();
});
$("input[value=' Prev ']").click(function() {
$("#divWiz > div").hide();
$("#divWiz > div:lt("+cutoff+")").show(); });
$("input[value=' Show All ']").click(function() {
$("#divWiz > div").show();
});
});
精彩评论