Say you filter a long series of photos of people according to age ranges (20-25, 26-30, 31-35...). Given that a user can permute to any range they want how could you make the showing/hiding efficient?
Edit: Here's my current code:
HTML:
<img src="http://..." age=""/>
jQuery:
var str = '';
$("#ageSelector option:selected").each(
function () {
str += $(this).attr("value") + "";
}
);
$('.photo').each(
function() {
var age = parseInt( $(this).attr("age") );
开发者_运维技巧 switch( str ){
case '18to24':
if( age <= 24 ){
$(this).show();
}
if( age > 24 ) {
$(this).hide();
}
break;
case '25to35':
if( age >= 25 || age <= 35 ) {
$(this).show();
}
if( age < 25 || age > 35 ){
$(this).hide();
}
break;
case '36to45':
if( age < 36 || age > 45 ){
$(this).hide();
}
if( age >= 36 || age <= 45 ){
$(this).show();
}
break;
case '45to50':
if( age < 45 || age > 50 ){
$(this).hide();
}
if( age >= 45 || age <= 50 ){
$(this).show();
}
break;
case 'moreThan50':
if( age < 50 ){
$(this).hide();
}
if( age >= 50 ) {
$(this).show();
}
break;
default:
$(this).show();
}
}
);
I'm not sure how you're storing age on the image, so I'll just assume that you have an HTML5-compliant data attribute on your IMG tag. It's also unclear how you're getting the range of acceptable values.
You haven't yet provided details on when all of this is happening. I'll assume it's on the change of your drop down.
$('#ageSelector').change(function() {
//Parse out min and max values from your drop down
var range = $(this).find('option:selected').val().split("to");
var min = parseInt(range[0]);
var max = parseInt(range[1]);
//To show just elements in the range
$('img.photo').filter(function() {
return $(this).data('age') >= min && $(this).data('age') <= max;
}).show();
//To show elements in the range and hide all others
$('img.photo').each(function() {
$this = $(this);
$this.toggle($this.data('age') >= min && $(this).data('age') <= max);
});
});
It's difficult to provide an exact answer without you providing more details of exactly what you're looking for, but is something like this along the right lines? Change the value in the select
element to filter the div
elements based on the selection.
It uses the jQuery filter
function to narrow down the selection based on the selected values, and hides all non-matching elements.
If you can have your images in a table ( and the age ) like :
var imgs= [ ["http://site/img1.jpg",32],
["http://site/img2.jpg",27],
["http://site/img5.jpg",24],
["http://site/img9.jpg",22] ];
And you have a container <div id="container"></div>
, you could do a function like :
function loadRange(a,b){
for(var i=0;i<imgs.length;i++)
{
if(imgs[i][1]>=a && imgs[i][1]<=b)
{
if(imgs[i][0]==null) $("#img"+i).show();
else
{
$("#container").append('<img src="'+encodeURI(imgs[i][0])+'" id="img'+i+'" />');
imgs[i][0]= null;
}
}
else if(imgs[i][0]==null) $("#img"+i).hide();
}
}
and call loadRange(20,24)
to load 20 to 24.
( to load only image once when needed )
精彩评论