我需要设置带有各种语言翻译的HTML标签的文本。我知道如何知道标签的ID,但我想制作一个不需要id的通用Javascript函数。按此顺序,我需要这样的事情:
HTML:
<label> <script> translating_function("hello"); </script> </label>
JAVASCRIPT:
function translating_function(string) {
//finding the translation (for example translated_text)
returning translated_text
}
应将translating_function函数的返回值设置为标签的文本。 有没有人知道怎么做。 非常感谢你。
答案 0 :(得分:1)
var voc = [
{
"AR":"أهلا",
"ES":"¡Hola",
"EN":"hello"
},
{
"AR":"مرحبا",
"ES":"bienvenida",
"EN":"welcome"
},
{
"AR":"و",
"ES":"y",
"EN":"and"
},
{
"AR":"في اللغة العربية",
"ES":"a España",
"EN":"to English"
}
];
function translate(ele,lng){
for(var i=0;i<voc.length;i++){
for(var k in voc[i]){
if(voc[i][k] == ele.innerText.trim()){
ele.innerText = voc[i][lng];
break;
}
}
}
}
function translateTo(lng){
var trc = document.getElementsByClassName("translatable");
for(var i=0;i<trc.length;i++){
translate(trc[i],lng);
}
}
//add this function to any event button.click,select.change or on load
//translateTo("AR");
&#13;
<p>
<span class='translatable'>hello</span>
<span class='translatable'>and</span>
<span class='translatable'>welcome</span>
<span class='translatable'>to English</span> :)
</p>
<select onchange='translateTo(this.value)'>
<option value='EN'>English</option>
<option value='AR'>Arabic</option>
<option value='ES'>Espain</option>
</select>
&#13;
答案 1 :(得分:0)
<script>
function translating_function(str) {
return 'translating: ' + str;
}
</script>
<label> <script> document.write(translating_function("hello")); </script> </label>