简体   繁体   English

记住HTML中用户区域设置选择的最简单方法

[英]Easiest way of remembering user locale selection in HTML

I've been working on a website of mine for about a week now. 我已经在我的网站上工作了大约一个星期。 I'm very good with HTML and CSS, but I'm still trying to wrap my head around Javascript, JQuery and PHP. 我对HTML和CSS很好,但是我仍在尝试围绕Javascript,JQuery和PHP展开讨论。

Basically, what I'm trying to do is create a way if remembering the users language and locale based on their selection on a language selection page. 基本上,我要尝试创建的一种方式是,根据用户在语言选择页面上的选择来记住用户的语言和语言环境。 What I'd like (if possible), is for a user to select their flag on a /locale page and make that change the url of the homepage (ie. mysite.com/en-us ). 我想要的(如果可能的话)是让用户在/ locale页面上选择其标志,并进行更改以更改主页的网址(即mysite.com/en-us )。 I'm going to be translating my website content via static pages, not active translation. 我将通过静态页面而非主动翻译来翻译我的网站内容。

This only has to work for the homepage, not subsequent pages, however it would be awesome if it did work for pages under different directories too. 这仅适用于主页,而不适用于后续页面,但是如果它也适用于不同目录下的页面,那将是很棒的。 You can view a live example of my newly constructed website here . 您可以在此处查看我新建网站的实时示例。

I'd prefer Javascript or JQuery, but honestly - when someone else is doing the hard part, I don't really have the right to be picky. 我更喜欢Javascript或JQuery,但老实说-当其他人在努力工作时,我真的没有权利挑剔。

Thank everyone very much in advance for any assistance. 提前非常感谢大家的帮助。

There's two ways to achieve this: Cookies or localStorage. 有两种方法可以实现此目的:Cookies或localStorage。 The easiest one is localStorage : 最简单的一种是localStorage

Here's two plain Javascript functions. 这是两个简单的Javascript函数。 The first runs onbodyload and check if the previous language choice (stored in the localStorage) was Spanish. 第一次运行onbodyload并检查先前的语言选择(存储在localStorage中)是否为西班牙语。 If not (or blank), the welcome appears in English. 如果不是(或为空白),则欢迎词以英语显示。

When you click a button, it runs the second function which changes the welcome language plus stores the choice in the localStorage. 当您单击一个按钮时,它将运行第二个功能,该功能更改欢迎语言,并将选择存储在localStorage中。

HTML HTML

<button onclick="language('en')">english</button>
<button onclick="language('spa')">spanish</button>

<h1><span id=welcome>text</span></h1>

JAVASCRIPT JAVASCRIPT

document.getElementsByTagName("body")[0].onload=function(){session()};

function session() {    
var result = localStorage.getItem("session");

if (result === 'spa') {
    document.getElementById("welcome").innerHTML = "Hola!";
} else {
    document.getElementById("welcome").innerHTML = "Hello!";
}
}

function language(key) {
if (key === 'en') {
    document.getElementById("welcome").innerHTML = "Hello!";
    localStorage.setItem("session", "en");
} else if (key === 'spa') {
    document.getElementById("welcome").innerHTML = "Hola!";
    localStorage.setItem("session", "spa");
}
}

Codepen DEMO Codepen演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM