Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

Javascript - Navigation as a loop

I would like to create a simple navigation:

<ul>
    <li><a href="#div1">Div1-name</a></li>
    <li><a href="#div2">Div2-name</a></li>
    <li><a href="#div3">Div3-name</a></li>
</ul>

When clicked, it goes to the div with that id. I don't want to do this permanently, it's supposed to change in the loop because the user can add new items and wants them to be looped.

The user adds new div - with a unique name and ID. How to construct a loop?

It's best to set a constant class for divs (e.g. gohere), you have to load it via javascript, then do li elements in a loop.

Can anyone help?

And these are the elements that the user adds:

<div class="divdiv" id="div_id">
    <h3>DIV TITLE</h3>
    <br>
        Description
    <br>
    <p>Description</p>
    <hr>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

OK, it's really difficult to understand exactly what you ask for, but here (a bit hacky) an example. I hope that it can help you in the right direction.

var items = document.getElementById('items');
var main = document.getElementById('main');

items.addEventListener('click', e => {
  e.preventDefault();
  if (e.target.nodeName == 'A') {
    console.log(`You clicked ${e.target.attributes['href'].value}`);
  }
});

document.forms.new.addEventListener('submit', e => {
  e.preventDefault();
  let newid = items.children.length + 1;
  console.log(newid);
  let li = `<li><a href="#div${newid}">Div${newid}-name</a></li>`;
  items.innerHTML += li;
  let div = `<div class="divdiv" id="div${newid}">
    <h3>DIV TITLE</h3><br>Description<br><p>Description</p><hr></div>`;
  main.innerHTML += div;
});
<ul id="items">
  <li><a href="#div1">Div1-name</a></li>
  <li><a href="#div2">Div2-name</a></li>
  <li><a href="#div3">Div3-name</a></li>
</ul>

<form name="new">
  <button>Add new</button>
</form>

<div id="main"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...