简体   繁体   中英

How to break if/else statement in JavaScript once a condition is true

So I have this basic JavaScript code to detect a user language and redirect to the proper page based on the browser language, the issue I am facing is that the if/else statement keeps going as an infinite loop and the browser keeps refreshing.

The code is set on a separate file and is included only in the en-US page, the code is a stand-alone, not using any function.

if(userLang == "en-US"){
  window.location.href = "domainame.com/faq.html";
}
else if(userLang == "nl"){
  window.location.href = "domainame.com/faq-de.html";
}
else if(userLang == "fr"){
  window.location.href = "domainame.com/faq-fr.html";
}
else if(userLang == "es-ES"){
  window.location.href = "domainame.com/faq-es.html";
}
else if(userLang == "ja"){
  window.location.href = "domainame/faq-ja.html";
}

I expect the browser to check for the user language and redirect to the proper page, instead, the browser keeps refreshing.

You can add an extra check to only change the page if it is not the current page.

Something like this:

let lanPage = '';
if(userLang == "en-US"){
  lanPage = "https://domainame.com/faq.html";
} else if(userLang == "nl"){
  lanPage = "https://domainame.com/faq-de.html";
} else if(userLang == "fr"){
  lanPage = "https://domainame.com/faq-fr.html";
} else if(userLang == "es-ES"){
  lanPage = "https://domainame.com/faq-es.html";
} else if(userLang == "ja"){
  lanPage = "https://domainame/faq-ja.html";
}

if(lanPage && lanPage !== location.href) {
  location.href = lanPage;
}

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