简体   繁体   中英

Change text of a tag when an option selected using Javascript

I want to make translations on my small site using Javascript. I would like to change tag content by its ID or smth like that. 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

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

en.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.

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> 

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