开发者问题收集

当我无法控制 html 时,如何向元素添加事件处理程序?

2015-09-18
102

我有一个带有下拉列表和链接标签的页面。

我根本无法修改页面上的 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>
3个回答

尝试这种方式,您可以将每种语言的文本存储在 option 元素中:

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>
Rayon
2015-09-18

如果您想翻译该按钮

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>

此处演示

jessegavin
2015-09-18
var a = document.querySelector('.goButton');
a.textContent = 'Changed';
Lee
2015-09-18