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

249
Views
Cómo reducir la repetición en la función jQuery para agregar URL al menú de alternancia de idioma

Estoy configurando un menú desplegable multilingüe sin acceso al lado del servidor. Es para un sitio de WordPress con Twig integrado, por lo que las sutilezas habituales de WP para manejar cosas como obtener las URL de inicio y ruta no están disponibles. Con esas limitaciones, jQuery parece ser la solución más viable.

Esto es lo que tengo hasta ahora: esto actualiza los atributos href en un menú desplegable para alternar entre cuatro sitios: inglés (predeterminado, ID de blog: 1), alemán, francés y español. El script a continuación funciona bien, pero me gustaría reducir la repetición si puedo. Poner los elementos .indexOf en una matriz duplica la cadena de dos letras del país en la URL, por lo que el código se encuentra en este estado súper repetitivo.

Idealmente, me gustaría tener una declaración if que verifique /de , /fr y /es ya que esos tres bloques son casi idénticos. De antemano, gracias por cualquier consejo.

 var langDropPathname = window.location.pathname.slice(3); // cut 2-letter country and slash from path for non-default sites var langDropPathEN = window.location.pathname; // path for default site var langDropDE = "/de"; var langDropFR = "/fr"; var langDropES = "/es"; if (window.location.href.indexOf("/de/") > -1) { $(".langDropEN").attr('href', langDropPathname); $(".langDropDE").attr('href', langDropDE+langDropPathname); $(".langDropFR").attr('href', langDropFR+langDropPathname); $(".langDropES").attr('href', langDropES+langDropPathname); if ($("body").hasClass("error404")) { document.location.href=langDropDE; } } else if (window.location.href.indexOf("/fr/") > -1) { $(".langDropEN").attr('href', langDropPathname); $(".langDropDE").attr('href', langDropDE+langDropPathname); $(".langDropFR").attr('href', langDropFR+langDropPathname); $(".langDropES").attr('href', langDropES+langDropPathname); if ($("body").hasClass("error404")) { document.location.href=langDropFR; } } else if (window.location.href.indexOf("/es/") > -1) { $(".langDropEN").attr('href', langDropPathname); $(".langDropDE").attr('href', langDropDE+langDropPathname); $(".langDropFR").attr('href', langDropFR+langDropPathname); $(".langDropES").attr('href', langDropES+langDropPathname); if ($("body").hasClass("error404")) { document.location.href=langDropES; } } else { $(".langDropEN").attr('href', langDropPathEN); $(".langDropDE").attr('href', langDropDE+langDropPathEN); $(".langDropFR").attr('href', langDropFR+langDropPathEN); $(".langDropES").attr('href', langDropES+langDropPathEN); }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Simplemente iterar sobre una matriz de ['/de', '/fr', '/es'] parece que funcionaría.

 const langs = ['/de', '/fr', '/es']; const lang = langs.find(substr => window.location.href.includes(substr)); const suffix = lang ? langDropPathname : langDropPathEN; $(".langDropEN").attr('href', suffix); $(".langDropDE").attr('href', langDropDE + suffix); $(".langDropFR").attr('href', langDropFR + suffix); $(".langDropES").attr('href', langDropES + suffix); if ($("body").hasClass("error404") && lang) { document.location.href = lang.slice(1); }

No conozco el contexto más amplio del código, pero sería aún mejor si pudiera juntar todos los idiomas, en lugar de seleccionar algunos específicos. Tal vez algo como

 const langs = { de: <content of langDropDE> fr: <content of langDropFR> ... }

para todos los idiomas, entonces

 const langEntry = Object.entries(langs) .find(entry => window.location.href.includes('/' + entry[0]));

y continúe desde allí, ahora que tiene la cadena de idioma coincidente y el langDrop en la entrada encontrada.

about 4 years ago · Juan Pablo Isaza Report

0

puede hacer coincidir con una expresión regular

 const langDropPathEN = window.location.pathname // path for default site , langDropPathname = langDropPathEN.slice(3) // cut 2-letter country and slash from path for non-default sites , LangDrop = { DE: '/de', FR: '/fr', ES: '/es' } , LangRegEx = new RegExp('/de/|/fr/|/es/') ; let lang = window.location.href.match(LangRegEx) if (!!lang) { $(".langDropEN").attr('href', langDropPathname); $(".langDropDE").attr('href', langDrop.DE +langDropPathname); $(".langDropFR").attr('href', langDrop.FR +langDropPathname); $(".langDropES").attr('href', langDrop.ES +langDropPathname); if ($("body").hasClass("error404")) document.location.href = lang[0].slice(0,3); } else { $(".langDropEN").attr('href', langDropPathEN); $(".langDropDE").attr('href', langDrop.DE +langDropPathEN); $(".langDropFR").attr('href', langDrop.FR +langDropPathEN); $(".langDropES").attr('href', langDrop.ES +langDropPathEN); }
about 4 years ago · Juan Pablo Isaza 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!