从ID的动态填充<ul>

时间:2019-01-08 18:05:41

标签: javascript jquery

我正在创建一个带有菜单的网页,以便使用其ID跳到不同的部分。我想拉这些ID来动态创建导航。我在其他地方使用jQuery,但是Vanilla JS也是一种选择。

是这样的:

NODE_TLS_REJECT_UNAUTHORIZED=0
This disables SSL checks so you can intercept your own SSL requests. This leaves you open to Man-in-The-Middle attacks and should NEVER make it to production, and I wouldn't even leave it in development for long. However, it will allow you to intercept the HTTP Requests.

HTTP_PROXY=http://127.0.0.1:8888
This sets node to utilize a proxy listening on your localhost at port 8888. Port 8888 is the default for Fiddler. Many other proxies default to 8080.

将导致创建以下内容:

<section id="foo">
   <h2>Foo</h2>
   ...
</section>
<section id="bar">
    <h2>Bar</h2>
    ...
</section>     

4 个答案:

答案 0 :(得分:0)

将要包含在导航栏中的节或元素放入。之后,获取ID并附加到ul中。

//iterate with tag name or assign some class
$('section').each(function(key, element){
   var elementID = element.attr('id');
   $('nav ul').append('<li><a href="#'+elementID+'"></a></li>');
});

答案 1 :(得分:0)

鉴于您所显示的HTML,这是一个简单的普通JS解决方案:

   class ParentButton(Button):
       def __init__(self, pos, **kwargs):
           super().__init__(**kwargs)
           self.size_hint = None, None
           self.pos = pos
      def on_release(self):
          self.add_widget(ChildButton())

  class ChildButton(Button):
      def __init__(self, **kwargs):
          super().__init__(**kwargs)
          self.size_hint = None, None
          self.pos = (0, 0)
      def on_release(self):
          if self.parent.pos[0] &lt; 150:
              self.pos = (150, 50)
          else:
              self.pos = (150, 150)

  class Layout(FloatLayout):
      def __init__(self, **kwargs):
          super().__init__(**kwargs)
          self.add_widget(ParentButton((100, 100)))
          self.add_widget(ParentButton((200, 100)))

  class TestApp(App):
      def build(self):
          return Layout()

  if __name__ == '__main__':
      TestApp().run()
const sections = document.querySelectorAll('section[id]');
const nav = document.createElement('nav');
const ul = document.createElement('ul');
for (const section of sections) {
  const li = document.createElement('li');
  const a = document.createElement('a');
  a.href = "#" + section.id;
  a.textContent = section.querySelector('h2').textContent;
  li.appendChild(a);
  ul.appendChild(li);
}
nav.appendChild(ul);
header.appendChild(nav);
#header nav { background: #f8f8f8; padding: 5px; }
#header ul { list-style-type: none; margin: 0; padding: 0;}
#header li { margin: 0; padding: 0 20px; display: inline-block; }
#header a { color: #666; text-decoration: none; }

答案 2 :(得分:0)

这里是jQuery的一个示例,试图将任务分解并使其易于遵循;

$(function() {
  //call the fancy function on page-ready
  generatenav().appendTo($("div"));
});

function generatenav() {
  var $sections = $("section"); //get the sections
  var $nav = $("<nav>"); //create the nav
  var $ul = $("<ul>"); //create the list
  $ul.appendTo($nav);
  $.each($sections, function(idx, elem) { //loop through the sections
    let $li = $("<li>"); //create the li-element
    $li.append(
      $("<a>")  //create the anchor
        .attr("href", `#${$(elem).attr("id")}`) //set the href
        .text($(elem).find("h2:first-child").text())) //set the text
        .appendTo($ul);
  });
  return $nav;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div></div>
<section id="foo">
  <h2>Foo</h2>
  ...
</section>
<section id="bar">
  <h2>Bar</h2>
  ...
</section>

答案 3 :(得分:0)

您可以使用Vanilla JS轻松实现此目标:

// Select all sections with IDs
var sections = document.querySelectorAll('section[id]');

for (var i = 0; i < sections.length; i++) {
  // Get the current section
  var section = sections[i];
  // Get the title inside that current section
  var title = section.querySelector('h2');
  var li = document.createElement('li');
  var a = document.createElement('a');
  a.setAttribute('href', '#' + section.id);
  var text = document.createTextNode(title.textContent);
  a.appendChild(text);
  li.appendChild(a);
  document.querySelector('nav ul').appendChild(li);
}
<nav>
  <ul></ul>
</nav>

<section id="foo">
  <h2>Foo</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam varius pulvinar mattis. Sed nec dui magna. Etiam elementum pellentesque mollis. Vestibulum varius, nulla et mattis imperdiet, quam nisi laoreet erat, eu tempus erat ex mollis nibh. Donec
    imperdiet lobortis diam, sed suscipit felis vestibulum id. Vestibulum tincidunt gravida augue nec convallis. Duis vel euismod urna. Aliquam porttitor, justo eget malesuada vestibulum, tellus nunc posuere libero, non facilisis enim sem quis tortor.
    Vivamus mollis luctus placerat. Phasellus sed lorem velit. Sed sit amet erat sit amet metus semper ullamcorper. Maecenas non erat ut mi ullamcorper tempor ut vitae tellus.</p>
</section>

<section id="bar">
  <h2>Bar</h2>
  <p>Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Suspendisse condimentum vel tellus scelerisque pretium. Cras a hendrerit nisl. Quisque ornare ante eget lorem malesuada interdum. Aliquam augue est, imperdiet eu
    est non, dictum volutpat ligula. Ut sed feugiat eros, id euismod risus. Vestibulum vel libero sit amet lorem eleifend varius. Aenean eu ultricies augue, a tempus lorem. Quisque nisl dolor, commodo nec fringilla non, fringilla sed erat. Fusce vitae
    rhoncus turpis, eget vestibulum dui. Quisque tempor magna luctus urna viverra fermentum. Aliquam accumsan sodales ligula, viverra rutrum diam tempus vitae. Vestibulum sem diam, laoreet at vulputate id, tristique nec mauris.
  </p>
</section>