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 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?