[英]How can i run JavaScript inside my webpage only once?
所以我正在嘗試為我的網頁實現自動語言轉換器。 但它會在不斷運行時不斷刷新頁面。 我只想運行這個腳本一次,這樣它就不會永遠刷新我的頁面。
我有這個腳本:
var language = navigator.language || navigator.userLanguage;
language = language.substring( 0, 2 );
if (language == "pt" || "pt-BR" || "pt-PT"){
window.location.href = "index.html";
}
else {
window.location.href = "indexEN.html"; //
}
它被稱為:
<!-- Auto Language -->
<script src="js/language.js"></script>
把它想象成你有一個無限循環,比如while (true) {}
——你需要做的是在某個時候跳出循環。 要跳出這個循環,您需要添加一個檢查以確保您尚未在預期的頁面上。 這將停止不斷的重定向。
var language = navigator.language || navigator.userLanguage
language = language.substring(0, 2)
var ptPage = 'index.html'
var enPage = 'indexEN.html'
// you're calling substring, so no need to check the variants
// your check was also incorrect :)
if (language == "pt") {
if (window.location.pathname !== '/' + ptPage) {
window.location.href = ptPage
}
} else if (window.location.pathname !== '/' + enPage) {
window.location.href = enPage
}
不知道這是否是最佳實踐,但您可以使用 localStorage。
if((localStorage.getItem('pageLoaded') ?? 'true') === 'true') {
alert('dsds')
localStorage.setItem('pageLoaded', 'false')
}
警報將執行一次
刷新頁面是您的代碼的一部分,您可以在此處看到
var language = navigator.language || navigator.userLanguage;// get users default language
language = language.substring( 0, 2 );
if (language == "pt" || "pt-BR" || "pt-PT"){
window.location.href = "index.html";
}
else {
window.location.href = "indexEN.html"; //loading another html file for users who use english
}
因此,由於您正在重新加載另一個 html 文件,您的 javascript 將再次運行。 一個解決方案是讓您的網頁成為 SPA(單頁應用程序)。 這樣你就不必重新加載任何東西(包括 javascript)。 您還可以在不實際加載新文件的情況下更改頁面內容和標題。 SPA 通常在 react 中完成(使用 react 路由),但您也可以制作 vanilla JS。 https://medium.com/altcampus/implementing-simple-spa-routing-using-vanilla-javascript-53abe399bf3c
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.