Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

248
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda