Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

256
Views
jQuery agregar clase .active en el menú

Tengo un problema.

Quiero agregar la clase "activa" en el menú de elementos cuando la página relativa está activada.

el menú es muy sencillo:

 <div class="menu"> <ul> <li><a href="~/link1/">LINK 1</a> <li><a href="~/link2/">LINK 2</a> <li><a href="~/link3/">LINK 3</a> </ul> </div>

En jQuery necesito verificar si la url es www.xyz.com/other/link1/

si es este, me gustaría agregar una clase, el elemento 'a' de link1.

Estoy probando muchas soluciones pero nada funciona.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Haga clic aquí para una solución en jsFiddle

Lo que necesita es obtener window.location.pathname como se mencionó y luego crear expresiones regulares a partir de él y probarlo con hrefs de navegación.

 $(function(){ var url = window.location.pathname, urlRegExp = new RegExp(url.replace(/\/$/,'') + "$"); // create regexp to match current url pathname and remove trailing slash if present as it could collide with the link in navigation in case trailing slash wasn't present there // now grab every link from the navigation $('.menu a').each(function(){ // and test its normalized href against the url pathname regexp if(urlRegExp.test(this.href.replace(/\/$/,''))){ $(this).addClass('active'); } }); });
over 4 years ago · Santiago Trujillo Report

0

Una forma más fácil para mí fue:

 var activeurl = window.location; $('a[href="'+activeurl+'"]').parent('li').addClass('active');

porque mis enlaces van a una URL absoluta, pero si sus enlaces son relativos, puede usar:

 window.location**.pathname**
over 4 years ago · Santiago Trujillo Report

0

Obtenga los elementos LI, recorra, verifique el HREF:

 $('.menu').find('a').each(function() { if($(this).attr('href').indexOf('www.xyz.com/other/link1/')>0) { $(this).addClass('active'); } })
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!