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

336
Views
Cómo cambiar el valor de una variable global cuando un usuario selecciona una opción

tengo el html a continuación donde dejo que el usuario elija entre dos opciones

 <div style="float:right; line-height:60px; margin-right:18px; color:#666;">Language <select name="lang2" id="lang2" style="width:100px;" autocomplete="off"> <option value="gr" selected>Greek</option> <option value="en">English</option> </select> </div>

Después de eso, inicializo una variable global que obtiene el valor "gr". Quiero cambiar el valor global según lo que elija el usuario en el menú desplegable (gr o en). En el evento de selección de cambios, probé el código a continuación, pero la variable Idioma solo cambia dentro de la función, pero afuera permanece sin cambios (Idioma = "gr";)

 <script type="text/javascript"> var Language = "gr"; function langChanged(lang) { if (lang !== Language) { Language = lang; return Language; } } $(document).ready(function () { Language = $('#lang2 option:selected').val(); $("#lang2").on("change", function () { if (confirm("The language will be changed.Are you sure?")) { if ($(this).val() == "gr") { langChanged("gr"); //Language="gr"; } else if ($(this).val() == "en") { langChanged("en"); //Language="en"; } } }); }); //Language remains "gr" var title = Language == 'gr' ? 'Greek title' : 'English title'; var title2 = Language == 'gr' ? 'Greek title2' : 'English title2'; alert (title);... alert (title2);... </scipt> ```
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Considere el siguiente ejemplo:

 $(function() { var Language = "gr"; function langChange(lang) { if (lang !== Language) { Language = lang; } return Language; } $("#lang2").on("change", function(e) { e.preventDefault(); if (confirm("The language will be changed. Are you sure?")) { langChange($(this).val()); } else { $(this).val(Language); } console.log(Language); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div style="float:right; line-height:60px; margin-right:18px; color:#666;">Language <select name="lang2" id="lang2" style="width:100px;" autocomplete="off"> <option value="gr" selected>Greek</option> <option value="en">English</option> </select> </div>

about 4 years ago · Juan Pablo Isaza Report

0

Debe actualizar todas sus variables globales después de cambiar el idioma. Las líneas que usan la variable Idioma no se vuelven a ejecutar automáticamente cuando actualiza las variables, por lo que debe actualizarlas. Por lo tanto, deberá agregar las líneas title y title2 dentro de su función.

 var Language; var title1; var title2; function langChanged(lang) { if (lang !== Language) { Language = lang; title1 = Language == 'gr' ? 'Greek title' : 'English title'; title2 = Language == 'gr' ? 'Greek title2' : 'English title2'; } } $(document).ready(function() { Language = $('#lang2 option:selected').val(); langChanged(Language); $("#lang2").on("change", function() { /* ... */ }); });

como lo haría

 var myLanguage; var myTranslations; var translations = { gr: { title: "Greek Title", title2: "Greek Title 2", }, en: { title: "English Title", title2: "English Title 2", }, } function updateGlobals(){ myTranslations = translations[myLanguage]; console.log(myTranslations.title); console.log(myTranslations.title2); } function langChanged(lang) { if (lang !== myLanguage) { myLanguage = lang; updateGlobals(); } } $(document).ready(function() { myLanguage = $('#lang2 option:selected').val(); langChanged(myLanguage); $("#lang2").on("change", function() { if (confirm("The language will be changed. Are you sure?")) { langChanged($(this).val()); } else { // reset it back to what it is since they cancelled it window.setTimeout(function () { $(this).val(myLanguage); }, 10); } }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div style="float:right; line-height:60px; margin-right:18px; color:#666;">Language <select name="lang2" id="lang2" style="width:100px;" autocomplete="off"> <option value="gr" selected>Greek</option> <option value="en">English</option> </select> </div>

about 4 years ago · Juan Pablo Isaza Report

0

En primer lugar, para que su Language variable se actualice, deberá pasarlo dentro de su función $(document).ready . De lo contrario, nunca se procesará y, por lo tanto, no actualizará el valor de su variable de idioma.

En este caso, he usado let en lugar de var ya que tienen un alcance de bloque y puedes trabajar fácilmente con este tipo de variables ya que son más intuitivas en mi opinión.

Al final, también debe mover var title y var title2 dentro de document.ready(function() .

Como mencioné antes en mi primera anotación, si los hubiera colocado fuera de su document.ready(function(), el DOM no se actualizará en absoluto con los datos que está tratando de cambiar. Personalmente, usaría Vanilla Javascript ya que no me gusta mucho Jquery.

JavaScript puro puede ser más rápido para manipular y seleccionar el DOM que jQuery.

JavaScript es procesado directamente por el navegador y reduce la sobrecarga que realmente tiene JQuery.

Espero que mi respuesta te ayude a resolver la duda.

 $(document).ready(function () { let Language = "gr"; let lang2Selector = document.getElementById("lang2"); // function langChanged(lang) { if (lang !== Language) { let value = lang; return value; } } lang2Selector.addEventListener("change", function () { let Language = this.options[this.selectedIndex].text; if (confirm("The language will be changed.Are you sure?")) { if (this.value == "gr") { langChanged("gr"); Language = "gr"; } else if (this.value == "en") { langChanged("en"); Language="en"; } } var title = Language == 'gr' ? 'Greek title' : 'English title'; var title2 = Language == 'gr' ? 'Greek title2' : 'English title2'; alert (title); alert (title2); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div style="float:right; line-height:60px; margin-right:18px; color:#666;">Language <select name="lang2" id="lang2" style="width:100px;" autocomplete="off"> <option value="gr" selected>Greek</option> <option value="en">English</option> </select> </div>

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!