I have following site structure
<div id="movies">
<a href="">
<div>content</div>
</a>
<a href="">
<div>content</div>
</a>
...
</div>
There can be up to 50 a tags
inside #movies
. I want to show only 10 and reveal another 10 if the user requests it.
So I came up with following jquery code.
var count = $("#movies a").length;
if(count > 10){
for(i = 11; i <= count; i++){
$('#movies a:nth-child('+i+')').hide();
}
$('#more').append('<a>show more</a>');
}
$('#more a').click(function(){
var hidden = $("#movies a").filter(":hidden");
var count = 0;
for(element in hidden){
if(count <= 10){
element.show();
}
}
});
But this gives me Uncaught TypeError: Object 0 has no method 'show'
. Any ideas why? What do I need to change/add to make the idea work?
You're using some practices which are a little weird:
nth-child
; just use $("#movies a").slice(10).hide()
. hidden.each(function() { ... })
and not a for in
loop. Here, you could also use .slice
to your advantage. count
; it's 0
all the time so the if
clause is always true. You can't loop using for(.. in ..)
since that loops over the properties. Use jQuerys each method:
hidden.each(function() {
var element = $(this);
if(count <= 10)
element.show();
});
Try a simpler solution like below,
$(function () {
$("#movies a:gt(9)").hide();
var $moviesA = $('#movies a');
$('#more a').click(function(){
var $visibleA = $("#movies a :visible"); //Edit: added a space
$moviesA.slice($visibleA.length, $visibleA.length + 10).show();
});
});
hidden
is a jQuery object. Don't loop over it using for..in
. Use .each
.
hidden.each(function(){
if(count <= 10){
$(this).show();
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.