doudao5287 2017-12-21 11:48
浏览 49
已采纳

尝试创建一个导航菜单,其中包含指向页面上每个<h2>标题的链接[关闭]

I'm trying to create a navigation menu using jQuery with links to each <h2> title on pages created and published in Wordpress. Some of these pages can get a bit lengthy so this navigation menu should make it quick and easy for visitors to jump to certain parts of it's content.

I've got it set up so that each <h2> title creates it's own unique ID by using it's content prefixed by "#" (i.e. "My title" would get the ID "#My title") using this piece of code below:

jQuery("h2").each(function(){
      var id = jQuery(this).html();
      jQuery(this).attr("id", "#" + id);
})

Basically step 1 of 10.. What's left is to create a function that loops trough each <h2> that exists on the page and then creates a menu item for each of those titles. I kind of understand javascript loops but I'm just not sure how to get this to actually create new elements like this.

I'm still a novice when it comes down to Javascript or even jQuery so I apologise if anything's unclear.

Anyways I hope somebody can point me in the right direction. Any help would be much appreciated.

  • 写回答

1条回答 默认 最新

  • doudichu1358 2017-12-21 12:15
    关注

    From what I understand, I'm guessing that you are trying to create a navigation menu at the top of the page where it creates links to each of your <h2> subheadings.

    I don't really know how wordpress works but here are some ways that it can be achieved in jquery:

    You should store your <h2> elements in an array. You can do this by adding the id as you make them. You don't need a loop for this! (Also, if I were you, I wouldn't add the # before the ID, because then you would have to write "##name" when you try to call the ID in javascript or css.)

    var arr = [];
    $("h2").each(function(){
        var id = $(this).html();
        $(this).attr("id", id);
        arr.push($(this).attr('id'));
    });
    

    Now that you have the data for your <h2> elements, you can just loop through it to create your list. First, just create an empty <ul id="nav"></ul> in javascript. Then, you can keep adding <li></li> in it with the h2 contents. To add the links, you just have to surround the text with an <a href='#name'></a>.

    So it would turn out to be something like this:

    for (i in arr) {
      $('ul#nav').append('<li><a href="#' + arr[i] + '">' + arr[i] + '</a></li>');
    }
    

    You can of course then make the css to style the unordered list, and it can serve as a nav. I hope that helps!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧