为页面生成导航并附加到适当的导航项

时间:2014-09-25 17:47:28

标签: javascript jquery html

目前我有一个手动更新的导航(非常痛苦)。我有一些东西设置为基于页面内容创建子导航。

问题是这对于一个页面当前只有用,因为我明确地检查了该页面类。无法绕过一种方式,使其更灵活地应用于所有页面。

我想要实现的目标的图片:

enter image description here 到目前为止,代码实现了这种预期的效果(请记住,它不是模块化的,只适用于这种情况):

   // create array to hold section IDs
   var $navlinksModule = [];
   // find each content section on the page
   // push it to the array created above
   $('.module').each(function(){
       $navlinksModule.push($(this).attr('id'));
   });


   // for each item in the array
   // create a nav link 
   // and append it to this particular nav
   for (var i = 0; i < $navlinksModule.length; i++) {
      $('.cc-nav').append('<li><a href="#' + $navlinksModule[i] + '">' + $navlinksModule[i] + '</a></li>');
   };

寻找它以执行以下操作:

  • 确定其所在的页面(每个页面都有一个特定于页面的类)
  • 存放(如有必要?)
  • 检查页面数据,存储其导航ID
  • 找到合适的导航部分
  • 将其应用于该导航部分。

所有帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

我认为你走在正确的轨道上。我会在数组中存储对象,因为它听起来你想要的不仅仅是一个数组真的很容易给你。然后,您可以在整理阵列的过程中进行其他测试:

$('.module').each(function(){
   // create an object...
   var theModule = {};
   theModule.id = $(this).attr('id');
   theModule.text = theModule.id;
   // vague guess, since I don't know how the rest of your markup works...
   // but this is where you'd add a flag that says if this module is the current one
   theModule.isCurrent = $('#divThatHasMyPageIdentifierClass').hasClass(theModule.id);
   // add the object to your array
   $navlinksModule.push(theModule);
});

您的其他要求更具投机性,我需要了解更多您的结构,以便更好地了解如何处理这些问题。请记住,如果将对象存储在数组中,则必须访问其属性进行比较,而不仅仅是对象。