2015-09-11 2 views
0

У меня есть простой неупорядоченный список, т. Е. Меню (с двумя уровнями подменю). Я хочу, чтобы его подменю (и подменю этих подменю) отображались в алфавитном порядке сверху вниз. HTML код меню выглядит следующим образом:Сортировка списка элементов по алфавиту

<div id="sidebar2" class="sidebar" > 
     <ul class="goo-collapsible goo-coll-stacked"> 
      <li class="header">Information Systems</li> 
     </ul> 
     <div > 

     <div id="nav"> 
     <ul id="navList"> 

      <li><a href="#">Other Databases and Portals</a> 
    <!-- This is the sub nav --> 
       <ul class="listTab"> 
       <li ><a href='http://www.icar.org.in/rohudatabase/index.php' target="_blank">Rohu Database</a></li> 
      <li ><a href='http://117.240.114.67/weedid/aiwsweedident.aspx' target="_blank">Weed Seed Identification</a></li> 
      <li ><a href='http://117.240.114.67/weedid/cwsmainweeds.aspx' target="_blank">Weed Seedling Identification</a></li> 
      <li ><a href='http://117.240.114.67/weedid/bwiweedident.aspx' target="_blank">Weed Identification</a></li> 

      <li ><a href='http://www.crida.in:8080/naip/index.jsp' target="_blank">Crop Pest DSS</a></li> 
      <li ><a href='http://www.cropweatheroutlook.in' target="_blank">Crop Weather Outlook: AICRPAM tools</a></li> 
      <li ><a href='http://www.nbfgr.res.in/Databases/formfish/index.html' target="_blank">Automated Species Identification System</a></li> 
      <li ><a href='http://www.nbfgr.res.in/Databases/ornamental/home.aspx' target="_blank">Marine ornamental finfishes and shell fishes</a></li> 
      <li ><a href='http://210.212.93.85/agris/breed.aspx' target="_blank">Animal Genetic Resources of India</a></li> 
      <li ><a href='http://www.ncipm.org.in/cropsap2014/login.aspx' target="_blank">Crop Pest Surveillance and Advisory</a></li> 
      <li ><a href='http://www.ncipm.org.in/ICTMalawi/' target="_blank">ICT Based Pest Surveillance</a></li> 
      <li ><a href='http://ctcri.in/statistics/FormsCEI.aspx' target="_blank">TUBER CROPS STATISTICS</a></li> 

      <li ><a href='http://www.crijaf.org.in/SideLinks/QuickLinks/AgrometeorologicalData.html' target="_blank">Agrometeorological Data at ICAR-CRIJA</a></li> 
      <li ><a href=' http://www.crida.in:8080/naip/index.jsp' target="_blank">Crop Pest DSS</a></li> 
      <li ><a href=' http://nrcgrapes.nic.in/weather_forecast_based_grape_adv.htm' target="_blank">Weather forecast based grape advice</a></li> 
      <li ><a href='http://research.ciphet.in/' target="_blank">Post-Harvest Machinery</a></li> 
      <li ><a href='http://cift.res.in/innercontent.php?contentid=NjA=' target="_blank">CIFT Knowledge Base</a></li> 
      <li ><a href='http://nrce.nic.in/breeds.php' target="_blank">Equine Breeds of India</a></li> 
    </ul> 
    </li> 
    <li><a href="#">Genetic Resources Portals</a> 
    <!-- This is the sub nav --> 
    <ul class="listTab"> 
    <li ><a href='http://www.mgrportal.org.in/' target="_blank">Microbial Genetic Resources Portal</a></li> 
      <li ><a href='http://www.nbpgr.ernet.in/PGR_Databases.aspx' target="_blank">PGR Database</a></li> 
      <li ><a href='http://www.nbpgr.ernet.in:8080/PGRPortal/(S(fzkcby45lxboum2hufans255))/default.aspx' target="_blank">PGR Portal</a></li> 
      <li ><a href='http://210.212.93.85/agrportal/index.htm' target="_blank">Animal Genetic Resources Portal</a></li> 
      <li ><a href='http://www.sugarcane.res.in/index.php/en/resrch/genetic-resources' target="_blank">Sugarcane Genetic Resources</a></li> 
    </ul> 
    </li> 
    </div> 
    </div> 
    <div style="margin-top: 65px;"> 
    <ul class="goo-collapsible goo-coll-stacked"> 
    <li class="header">Latest News</li> 
    <marquee direction="up" style = "width:100%;margin:0px;padding:0px;" scrolldelay="200" onMouseOver="this.stop();" onMouseOut="this.start();"> 
    <li><a href="PDF/Digitization AICRPs Information.pdf" target="_blank" >Digitization AICRPs Information</a></li> 
    <li><a href="PDF/Draft Format for Technology Database.pdf" >Draft Format for Technology Database</a></li> 
    <li><a href="PDF/ICAR Guidelines Research Papers 2014.pdf" >ICAR Guidelines Research Papers 2014</a></li> 
    <li><a href="PDF/Letter for Nomination of Nodal officers.pdf" >Letter for Nomination of Nodal officers</a></li> 
    <li><a href="PDF/Mapping of Natural Resources.pdf" >Mapping of Natural Resources</a></li> 
    <li><a href="JavaScript:display('Circular');" >Circular</a></li> 
    </marquee> 
    </ul> 
    </div> 
</div> 

здесь div меню которого я хочу быть отсортирован это одна с id=nav (остальные являются колонтитулы в меню).
Пожалуйста, помогите мне в этом.

+1

Какой язык программирования? – jdweng

+0

html или jquery! –

ответ

0

Сортировка коллекций HTML может быть проблематичной, но я думаю, что смогу решить эту интересную задачу для вас. Ну, идея состоит в том, чтобы преобразовывать коллекции в массивы и сортировать массивы, так как сортировка внутри объектов/коллекций бессмысленна в JS.

Затем мы просто воссоздаем всю структуру на основе отсортированных массивов и вставим ее на страницу вместо предыдущей. Часть HTML - это только ваш html-ввод. В JS-части я использовал JQuery. sortItems(arr) - вспомогательная функция. Я использую jQuery.map для преобразования коллекций объектов списка в массивы объектов списка. Здесь у вас 1 уровень гнездования, и я представил новое свойство на внешнем li - arrayChildren - для хранения вложенных списков в виде массивов. В конце концов, я просто перебираю свой массив и воссоздаю вложенные списки из свойства arrayChildren.

Ну, это решает, что вы просили, хотя функциональность довольно простая.

$(document).ready(function() { 
 
    function sortItems(arr) { 
 
     arr.sort(function(el1, el2) { 
 
      if(el1.childNodes[0].innerText > el2.childNodes[0].innerText) return 1; 
 
      if(el1.childNodes[0].innerText < el2.childNodes[0].innerText) return -1; 
 
      return 0; 
 
     }); 
 
    } 
 
    var items = jQuery.map($("#nav ul#navList > li"), function(el) { 
 
     return el; 
 
    }); 
 
    for(var i = 0; i < items.length; i++) { 
 
     items[i].arrayChildren = jQuery.map(items[i].childNodes[4].children, function(el) { 
 
      return el; 
 
     }); 
 
     sortItems(items[i].arrayChildren); 
 
    } 
 
    sortItems(items); 
 
    var docfrag = document.createDocumentFragment(); 
 
    $.each(items, function(key, value) { 
 
     var ul = $("ul").addClass("listTab"); 
 
     $.each(value.arrayChildren, function(key, val) { 
 
      $(value).find("ul.listTab").append(val); 
 
     }); 
 
     $(docfrag).append(value); 
 
    }); 
 
    $("#nav ul#navList").append(docfrag); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="sidebar2" class="sidebar" > 
 
     <ul class="goo-collapsible goo-coll-stacked"> 
 
      <li class="header">Information Systems</li> 
 
     </ul> 
 
     <div > 
 

 
     <div id="nav"> 
 
     <ul id="navList"> 
 

 
      <li><a href="#">Other Databases and Portals</a> 
 
    <!-- This is the sub nav --> 
 
       <ul class="listTab"> 
 
       <li ><a href='http://www.icar.org.in/rohudatabase/index.php' target="_blank">Rohu Database</a></li> 
 
      <li ><a href='http://117.240.114.67/weedid/aiwsweedident.aspx' target="_blank">Weed Seed Identification</a></li> 
 
      <li ><a href='http://117.240.114.67/weedid/cwsmainweeds.aspx' target="_blank">Weed Seedling Identification</a></li> 
 
      <li ><a href='http://117.240.114.67/weedid/bwiweedident.aspx' target="_blank">Weed Identification</a></li> 
 

 
      <li ><a href='http://www.crida.in:8080/naip/index.jsp' target="_blank">Crop Pest DSS</a></li> 
 
      <li ><a href='http://www.cropweatheroutlook.in' target="_blank">Crop Weather Outlook: AICRPAM tools</a></li> 
 
      <li ><a href='http://www.nbfgr.res.in/Databases/formfish/index.html' target="_blank">Automated Species Identification System</a></li> 
 
      <li ><a href='http://www.nbfgr.res.in/Databases/ornamental/home.aspx' target="_blank">Marine ornamental finfishes and shell fishes</a></li> 
 
      <li ><a href='http://210.212.93.85/agris/breed.aspx' target="_blank">Animal Genetic Resources of India</a></li> 
 
      <li ><a href='http://www.ncipm.org.in/cropsap2014/login.aspx' target="_blank">Crop Pest Surveillance and Advisory</a></li> 
 
      <li ><a href='http://www.ncipm.org.in/ICTMalawi/' target="_blank">ICT Based Pest Surveillance</a></li> 
 
      <li ><a href='http://ctcri.in/statistics/FormsCEI.aspx' target="_blank">TUBER CROPS STATISTICS</a></li> 
 

 
      <li ><a href='http://www.crijaf.org.in/SideLinks/QuickLinks/AgrometeorologicalData.html' target="_blank">Agrometeorological Data at ICAR-CRIJA</a></li> 
 
      <li ><a href=' http://www.crida.in:8080/naip/index.jsp' target="_blank">Crop Pest DSS</a></li> 
 
      <li ><a href=' http://nrcgrapes.nic.in/weather_forecast_based_grape_adv.htm' target="_blank">Weather forecast based grape advice</a></li> 
 
      <li ><a href='http://research.ciphet.in/' target="_blank">Post-Harvest Machinery</a></li> 
 
      <li ><a href='http://cift.res.in/innercontent.php?contentid=NjA=' target="_blank">CIFT Knowledge Base</a></li> 
 
      <li ><a href='http://nrce.nic.in/breeds.php' target="_blank">Equine Breeds of India</a></li> 
 
    </ul> 
 
    </li> 
 
    <li><a href="#">Genetic Resources Portals</a> 
 
    <!-- This is the sub nav --> 
 
    <ul class="listTab"> 
 
    <li ><a href='http://www.mgrportal.org.in/' target="_blank">Microbial Genetic Resources Portal</a></li> 
 
      <li ><a href='http://www.nbpgr.ernet.in/PGR_Databases.aspx' target="_blank">PGR Database</a></li> 
 
      <li ><a href='http://www.nbpgr.ernet.in:8080/PGRPortal/(S(fzkcby45lxboum2hufans255))/default.aspx' target="_blank">PGR Portal</a></li> 
 
      <li ><a href='http://210.212.93.85/agrportal/index.htm' target="_blank">Animal Genetic Resources Portal</a></li> 
 
      <li ><a href='http://www.sugarcane.res.in/index.php/en/resrch/genetic-resources' target="_blank">Sugarcane Genetic Resources</a></li> 
 
    </ul> 
 
    </li> 
 
    </div> 
 
    </div> 
 
    <div style="margin-top: 65px;"> 
 
    <ul class="goo-collapsible goo-coll-stacked"> 
 
    <li class="header">Latest News</li> 
 
    <marquee direction="up" style = "width:100%;margin:0px;padding:0px;" scrolldelay="200" onMouseOver="this.stop();" onMouseOut="this.start();"> 
 
    <li><a href="PDF/Digitization AICRPs Information.pdf" target="_blank" >Digitization AICRPs Information</a></li> 
 
    <li><a href="PDF/Draft Format for Technology Database.pdf" >Draft Format for Technology Database</a></li> 
 
    <li><a href="PDF/ICAR Guidelines Research Papers 2014.pdf" >ICAR Guidelines Research Papers 2014</a></li> 
 
    <li><a href="PDF/Letter for Nomination of Nodal officers.pdf" >Letter for Nomination of Nodal officers</a></li> 
 
    <li><a href="PDF/Mapping of Natural Resources.pdf" >Mapping of Natural Resources</a></li> 
 
    <li><a href="JavaScript:display('Circular');" >Circular</a></li> 
 
    </marquee> 
 
    </ul> 
 
    </div> 
 
</div>

1

Ответ может быть простым и элегантным с угловой JS, так и можно применить собственные фильтры «нг-повтор» директива. В этом случае вам нужно «orderBy». См ссылки API https://docs.angularjs.org/api/ng/filter/orderBy

function ctrl($scope) { 
 
    $scope.filter = 'name'; 
 
    $scope.alphabeticalReverse = false; 
 
    $scope.menuItems = [{ 
 
     name: 'itemB', 
 
     link: 'https://stackoverflow.com/', 
 
     submenue: [{ 
 
      name: 'subItemZ', 
 
      link: 'https://stackoverflow.com/' 
 
     }, 
 
     { 
 
      name: 'subItemA', 
 
      link: 'https://stackoverflow.com/' 
 
     } 
 
     ] 
 
    }, 
 
    { 
 
     name: 'itemC', 
 
     link: 'https://stackoverflow.com/' 
 
    }, 
 
    { 
 
     name: 'itemA', 
 
     link: 'https://stackoverflow.com/' 
 
    } 
 
    ]; 
 
}
<!DOCTYPE html> 
 
<html ng-app> 
 

 
<head> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
    <meta charset=utf-8 /> 
 
    <title>Angular JS Demo</title> 
 
</head> 
 

 
<body ng-controller="ctrl"> 
 
    <ul class="main-menu"> 
 
    <li ng-repeat="item in menuItems | orderBy: filter:alphabeticalReverse"> 
 
     <a ng-href="{{item.link}}">{{item.name}}</a> 
 
     <ul class="sub-menu"> 
 
     <li ng-repeat="subItem in item.submenue | orderBy:filter:!alphabeticalReverse"> 
 
      <a ng-href="{{subItem.link}}">{{subItem.name}}</a> 
 
     </li> 
 
     </ul> 
 
    </li> 
 
    </ul> 
 
</body> 
 

 
</html>

Смежные вопросы