简体   繁体   English

使用Javascript选择选项时更改标签的文本

[英]Change text of a tag when an option selected using Javascript

I want to make translations on my small site using Javascript. 我想使用Javascript在我的小型网站上进行翻译。 I would like to change tag content by its ID or smth like that. 我想通过它的ID或smth来更改标签内容。 I am not sure how should I do, but I kinda understand how it works... I want to create files with strings & translations for each langauge. 我不确定应该怎么做,但我有点理解它的工作原理...我想为每个语言创建带有字符串和翻译的文件。

So, there is a select tag which has who options... 因此,有一个选择标签,其中包含谁的选项...

    <select>
<option id="RU">Russian</option>
<option id="EN">English</option>
</select>

And there is content which has to be translated dependingly on selected option... 某些内容必须根据所选选项进行翻译...

<div>
<span id="stringName">Your Name EN</span>: Viktor
<span id="stringPhone">Your Phone EN</span>: +7 900 00 00 00
<span id="stringEmail">Your E-mail EN</span>: the_great_russia@russia.ru
</div>

And localization files like... 还有本地化文件,例如...

ru.js ru.js

stringName: "Your Name RU"
stringPhone: "Your Phone RU"
stringEmail: "Your E-mail RU"

en.js zh.js

stringName: "Your Name EN"
stringPhone: "Your Phone EN"
stringEmail: "Your E-mail EN"

I have searched for what I need, but couldn't find. 我已经搜索了需要的东西,但是找不到。

Hope you will help me :) Thanks. 希望你能帮助我:)谢谢。

Here is a very simple example of how you can get this to work using a change event on the select and a few global objects containing your language strings. 这是一个非常简单的示例,说明如何使用select和包含您的语言字符串的一些全局对象上的change事件使此方法起作用。

For your own site you can move the language objects to their own files and include them into the page 对于您自己的网站,您可以将语言对象移至其自己的文件,并将其包含在页面中

 var langRU = { stringName: "Your Name RU", stringPhone: "Your Phone RU", stringEmail: "Your E-mail RU" }; var langEN = { stringName: "Your Name EN", stringPhone: "Your Phone EN", stringEmail: "Your E-mail EN" }; function changeLang(lang) { document.querySelectorAll('[lang-change]').forEach(function(el) { el.innerText = window['lang'+lang][el.getAttribute('lang-change')]; }); } changeLang('EN'); 
 <select onchange="changeLang(this.value)"> <option value="RU">Russian</option> <option value="EN" selected>English</option> </select> <br><br><br> <div> <span lang-change="stringName">Your Name</span>: Viktor<br> <span lang-change="stringPhone">Your Phone</span>: +7 900 00 00 00<br> <span lang-change="stringEmail">Your E-mail</span>: the_great_russia@russia.ru<br> </div> 

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

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