如何保存切换的类名?

时间:2017-02-18 19:33:11

标签: javascript php html css

我试图制作一个功能来切换我网站的语言。我通过使用JavaScript切换类来实现这一点,但是如果我重新加载页面或转到另一个页面,则会更改回原始页面。如何保存JavaScript所做的更改?



gulp

function langToggle() {
  if (document.getElementById("contenten").className == "show") {
    document.getElementById("contenten").className = "hide";
    document.getElementById("contentnl").className = "show";
    document.getElementById("myBtn").value = "Nederlands";

  } else{
    document.getElementById("contenten").className = "show";
    document.getElementById("contentnl").className = "hide";
    document.getElementById("myBtn").value = "English";
  }
}

.hide{
	display: none;
}

.show{
	display: block;
}




我只想使用JavaScript或PHP

3 个答案:

答案 0 :(得分:0)

你的问题实际上是关于sessionStorage(html5功能,即使在IE8上也支持!!!!)。有关此功能的更多信息:https://developer.mozilla.org/en/docs/Web/API/Window/sessionStorage

在你的情况下:

function langToggle() {
  var isNederlands = document.getElementById("contenten").className == "show";
  document.getElementById("myBtn").value = sessionStorage["lang"] = isNederlands ? "Nederlands" : "English";

  if (document.getElementById("contenten").className == "show") {
    document.getElementById("contenten").className = "hide";
    document.getElementById("contentnl").className = "show";

  } else{
    document.getElementById("contenten").className = "show";
    document.getElementById("contentnl").className = "hide";
  }

}

然后..在您的页面Load事件:

document.getElementById("myBtn").value = sessionStorage["lang"];

答案 1 :(得分:0)

您可以在javascript中使用cookiessessionStorage

答案 2 :(得分:0)

您可以使用localStorage(或sessionStorage,具体取决于您是否希望在浏览器关闭时将其清除),如下所示:

// Update the display on page load
document.addEventListener("DOMContentLoaded", showLang);

function showLang() {
    // read the last saved language, defaults to 'en'
    var lang = localStorage.getItem('lang') || 'en';
    document.getElementById("contenten").className = lang == 'en' ? 'show' : 'hide';
    document.getElementById("contentnl").className = lang == 'nl' ? 'show' : 'hide';
    document.getElementById("myBtn").textContent = lang == 'nl' ? 'To English' : "Naar Nederlands";
}

function langToggle() {
    // read, toggle and update the language in local storage
    localStorage.setItem('lang', localStorage.getItem('lang') == 'en' ? 'nl' : 'en');
    // adapt the display accordingly
    showLang();
}

请注意,该按钮没有value属性,您需要使用textContent