我有一个带有下拉列表和链接标记的页面。
我根本无法修改页面上的html,但我可以在页面上添加javascript。
当用户从下拉列表中选择其他语言选项时,我需要能够翻译.goButton
元素的文本。
如何仅使用javascript完成此操作?
<a class="goButton" ... >Send</a>
<select name="ddlLanguages" id="ddlLanguages" class="form-control">
<option value="zh-CN">Chinese (Simplified, PRC)</option>
<option selected="selected" value="en-GB">English (United Kingdom)</option>
<option value="en-US">English (United States)</option>
<option value="fr-FR">French (France)</option>
<option value="de-DE">German (Germany)</option>
<option value="it-IT">Italian (Italy)</option>
<option value="pt-BR">Portuguese (Brazil)</option>
<option value="es-ES">Spanish (Spain)</option>
</select>
答案 0 :(得分:3)
以这种方式尝试,您可以在选项元素中存储每种语言的文本:
document.getElementById('ddlLanguages').addEventListener('change', function (elem) {
document.querySelector("a.goButton").innerHTML =
this.options[this.selectedIndex].getAttribute('data-action');
});
<select name="ddlLanguages" id="ddlLanguages" class="form-control">
<option data-action='发送' value="zh-CN">Chinese (Simplified, PRC)</option>
<option data-action='BritishSend' elected="selected" value="en-GB">English (United Kingdom)</option>
<option selected data-action="AmericanSend" value="en-US">English (United States)</option>
<option data-action="Envoyer" value="fr-FR">French (France)</option>
<option data-action="Senden" value="de-DE">German (Germany)</option>
<option data-action="Inviare" value="it-IT">Italian (Italy)</option>
<option data-action="Enviar" value="pt-BR">Portuguese (Brazil)</option>
<option data-action="Enviar" value="es-ES">Spanish (Spain)</option>
</select>
<a onclick="fillSearch()" class="goButton">AmericanSend</a>
答案 1 :(得分:2)
如果您正尝试翻译该按钮
JAVASCRIPT
function changeLanguage(e) {
var lang = e.target.options[e.target.selectedIndex].value;
var textMap = {
"en-US" : "send",
"en-GB" : "send",
"fr-FR" : "envoyer",
"zh-CN" : "发送",
"de-DE" : "senden",
"de-DE" : "senden",
"it-IT" : "inviare",
"pt-BR" : "mandar",
"es-ES" : "enviar"
};
if (lang && textMap[lang]) {
document.querySelector(".goButton").innerText = textMap[lang];
}
}
document.getElementById("ddlLanguages").addEventListener("change", changeLanguage);
<强> HTML 强>
<select name="ddlLanguages" id="ddlLanguages" class="form-control">
<option value="zh-CN">Chinese (Simplified, PRC)</option>
<option selected="selected" value="en-GB">English (United Kingdom)</option>
<option value="en-US">English (United States)</option>
<option value="fr-FR">French (France)</option>
<option value="de-DE">German (Germany)</option>
<option value="it-IT">Italian (Italy)</option>
<option value="pt-BR">Portuguese (Brazil)</option>
<option value="es-ES">Spanish (Spain)</option>
</select>
<强> DEMO HERE 强>
答案 2 :(得分:1)
var a = document.querySelector('.goButton');
a.textContent = 'Changed';
答案 3 :(得分:1)
使用查询选择器
document.querySelector(".goButton").innerHTML="Send 2";
这将基于CSS选择器
查询元素文档
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector