Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...