This is my code:
let navi = document.createElement("nav"); let navItems = { home:"/", my_profile:"/me" }; let btnClasses = ["bttn-minimal","bttn-md","bttn-primary"]; const redirector = ()=>{ window.history.pushState(null,null,this.getAttribute("data-to")); }; for(let i in navItems){ let navItem = document.createElement("button"); for(let c=0;c<btnClasses.length;c++){ navItem.classList.add(btnClasses[c]); } navItem.innerHTML = i.toUpperCase().replace(/_/g," "); navItem.setAttribute("data-to",navItems[i]); navItem.classList.add("navi-item"); navItem.addEventListener("click",redirector); navi.appendChild(navItem); } document.getElementById("navi").appendChild(navi);
The navItem.addEventListener("click",redirector);
is not working. The script tag is at the end of the body tag. I also tried using
navItem.onclick = redirector;
and it's the same. Not only it's not working i can't see the event listener in the chrome dev tools. Please help.
I tried using a regular function but it's same. Two reasons:
Also, i'm calling that code from a Browserify local require.
Your problem is that you use an Arrow function as the event handler.
Arrow functions do not have their own this
object; instead, they use the this
of the scope around them.
If you need this
in the event handler, use a regular function instead of an arrow function.
const redirector = function () {
window.history.pushState(null,null,this.getAttribute("data-to"));
};
Your event listener works just fine:
let navi = document.createElement("nav"); let navItems = { home:"/", my_profile:"/me" }; let btnClasses = ["bttn-minimal","bttn-md","bttn-primary"]; const redirector = ()=>{ alert('click!'); //window.history.pushState(null,null,this.getAttribute("data-to")); }; for(let i in navItems){ let navItem = document.createElement("button"); for(let c=0;c<btnClasses.length;c++){ navItem.classList.add(btnClasses[c]); } navItem.innerHTML = i.toUpperCase().replace(/_/g," "); navItem.setAttribute("data-to",navItems[i]); navItem.classList.add("navi-item"); navItem.addEventListener("click",redirector); navi.appendChild(navItem); } document.getElementById("navi").appendChild(navi);
<div id="navi"></div>
But as Xufox and PeterMader mentioned this
did not refer to the clicked button...
You might workaround this way:
const redirector = e => {
window.history.pushState(null, null, e.target.getAttribute("data-to"));
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.