基於jQuery實現點擊列表加載更多效果


<!DOCTYPE html>
< html xmlns = "http://www.w3.org/1999/xhtml" >
< head >
   < meta http-equiv = "Content-Type" content = "text/html; charset=utf-8" />
   < title >jquery showMore 顯示更多</ title >
   < script type = "text/javascript" src = "js/jquery-1.8.3.js" ></ script >
   < script type = "text/javascript" src = "js/jquery.showMore.js" ></ script >
</ head >
< body >
   < ul class = "showMoreNChildren" pagesize = "5" >
     < li >a</ li >
     < li >b</ li >
     < li >c</ li >
     < li >d</ li >
     < li >e</ li >
     < li >f</ li >
     < li >g</ li >
     < li >h</ li >
     < li >i</ li >
     < li >j</ li >
     < li >k</ li >
     < li >m</ li >
     < li >a</ li >
     < li >b</ li >
     < li >c</ li >
     < li >d</ li >
     < li >e</ li >
     < li >f</ li >
     < li >g</ li >
     < li >h</ li >
     < li >i</ li >
     < li >j</ li >
     < li >k</ li >
     < li >m</ li >
   </ ul >
  
   < ul class = "mynews" pagesize = "4" >
     < li >news 11</ li >
     < li >news 12</ li >
     < li >news 13</ li >
     < li >news 14</ li >
     < li >news 21</ li >
     < li >news 22</ li >
     < li >news 23</ li >
     < li >news 24</ li >
     < li >news 31</ li >
     < li >news 32</ li >
     < li >news 33</ li >
     < li >news 34</ li >
   </ ul >
  
   < script type = "text/javascript" >
     //調用顯示更多插件。參數是標准的 jquery 選擇符
     $.showMore(".showMoreNChildren,.mynews");
   </ script >
</ body >
</ html >
JavaScript code
  
(function () {
   var showMoreNChildren = function ($children, n) {
     //顯示某jquery元素下的前n個隱藏的子元素
     var $hiddenChildren = $children.filter(":hidden");
     var cnt = $hiddenChildren.length;
     for (var i = 0; i < n && i < cnt ; i++) {
       $hiddenChildren.eq(i).show();
     }
     return cnt - n;//返回還剩余的隱藏子元素的數量
   }
  
   jQuery.showMore = function (selector) {
     if (selector == undefined) { selector = ".showMoreNChildren" }
     //對頁中現有的 class = showMorehandle 的元素,在之后添加顯示更多條,並綁定點擊行為
     $(selector).each(function () {
       var pagesize = $(this).attr("pagesize") || 10;
       var $children = $(this).children();
       if ($children.length > pagesize) {
         for (var i = pagesize; i < $children.length; i++) {
           $children.eq(i).hide();
         }
  
         $("< div class = 'showMorehandle' >顯示更多</ div >").insertAfter($(this)).click(function () {
           if (showMoreNChildren($children, pagesize) <= 0) {
             //如果目標元素已經沒有隱藏的子元素了,就隱藏“點擊更多的按鈕條”
             $(this).hide();
           };
         });
       }
     });
   }
})();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM