0

我有以下网站结构

<div id="movies">

     <a href="">
         <div>content</div>
     </a> 
     <a href="">
         <div>content</div>
     </a>
     ...    

</div>

a tags里面最多可以有50个#movies。如果用户要求,我只想显示 10 个并显示另外 10 个。

所以我想出了以下jquery代码。

   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();
           }
       }
   });

但这给了我Uncaught TypeError: Object 0 has no method 'show'。任何想法为什么?我需要更改/添加什么才能使这个想法生效?

4

4 回答 4

6

您正在使用一些有点奇怪的做法:

  • 不要使用带有nth-child;的循环。只需使用$("#movies a").slice(10).hide().
  • 使用hidden.each(function() { ... })而不是for in循环。在这里,您也可以.slice发挥自己的优势。
  • 你不增加count; 一直如此0,因此该if子句始终为真。
于 2012-06-08T20:53:46.617 回答
5

您不能循环使用for(.. in ..),因为它会循环属性。使用 jQuerys 每种方法:

hidden.each(function() {
     var element = $(this);
     if(count <= 10)
        element.show();
});
于 2012-06-08T20:53:55.947 回答
2

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();
   });
});

DEMO: http://jsfiddle.net/fKuGT/1

于 2012-06-08T20:57:10.403 回答
0

hidden is a jQuery object. Don't loop over it using for..in. Use .each.

hidden.each(function(){
    if(count <= 10){
        $(this).show();
    }
});
于 2012-06-08T20:54:28.993 回答