Home > front end >  When I go to click it gives me the wrong array position
When I go to click it gives me the wrong array position

Time:11-07

I'm trying to make a website with pseudo routes and when I go to create my navigation bar it should insert me as a click the route in the position of the current array, when instead it always inserts me its last position.

This is my main code:

function loadHTML(path){
    console.log(path);
  fetch(path)
    .then(response=> response.text())
    .then(text=> document.getElementById("root").innerHTML=text);
}
const routes={
    home: "./core/pages/home.html",
    about: "./core/pages/about.html",
    contact: "./core/pages/contact.html"
}
function loadNav(){
    var nav=document.getElementById("nav");
    for(r in routes){
        var li=document.createElement("li");
        li.innerHTML=r;
        console.log(routes[r]);
        li.onclick=()=>{
            console.log(routes[r]);
        }
        nav.append(li);
    }
}
loadNav();

I tried to fix with the addeventlistener (even though I knew it didn't work anyway), but I can't find any answer to this damn problem

CodePudding user response:

Declare your variables and never use var

function loadNav(){
    var nav=document.getElementById("nav");
    for(const r in routes){
        const li = document.createElement("li");
        li.innerHTML=r;
        console.log(routes[r]);
        li.onclick=()=>{
            console.log(routes[r]);
        }
        nav.append(li);
    }
}

You've made r global so it always used the last value

  • Related