简体   繁体   中英

Target the css class with some JS

Hello I currently have this inline JS on my wordpress navigation menu

<a href="https://example.com/login/" onclick="window.location = 'https://example.com/login/?redirect_to='+window.location.href; return false;">login</a>

I was told it is better to use a regular menu item then just give it a class then target the class with some JS. I tried searching for examples but can't find that works for me. Could someone share a sample code to point me in the right direction?

thanks

I think this is what you are told.

 var link = document.querySelector(".js-link"); link.addEventListener("click", (e) => { e.preventDefault(); //do whatever you want hear console.log("redirect to another page"); });
 <a href="http://www.google.com" class="js-link">Google</a>

The way you do will make your code messy, hard to read and maintain. So we should separate html, css and js code. And to make your javascript and style not affect each other when you change your code, you should naming the class which you want to use javascript different with class you want to style.

For example I using class "js-link" just for javascript, not to style it. If I want to style the link I will add another class for it.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM