javascript - 如何为焦点和焦点 Javascript 的 <option> 设置不同的值

标签 javascript html html-select

这可能吗?

enter image description here

我有:

var titles = ["opt1 (beginner)", "opt2 (intermediate)", "opt3 (prof)"]
var select = document.getElementById('select');
for (i = 0; i < titles.length; i++) {
  var option = document.createElement("option");
  option.textContent = titles[i];
  select.append(option);
}
select.options[select.selectedIndex].innerHTML = "option1"

select.onfocus = function(){
for (i = 0; i < titles.length; i++) {
  select.options[i].textContent = titles[i];
}
};
<select id="select"></select>

这显示了标题中定义的选项值。

<select>在焦点上时,应该向我显示标题中定义的完整值,而当 select 未在焦点上时,我希望它显示不同的内容,因此在本例中是 option1 而不是 opt1(初学者)。

我尝试添加这个:

select.options[select.selectedIndex].innerHTML = "option1"

select.onfocus = function(){
for (i = 0; i < titles.length; i++) {
  select.options[i].textContent = titles[i];
}
};

还尝试了 onchange 事件,但到目前为止没有任何效果。

这是一个 fiddle

最佳答案

是的,这是可能的。使用 onblur 事件 http://www.w3schools.com/jsref/event_onblur.asp .这是一个基于您的 fiddle 的示例:

var titlesBlur = ["option 1", "option 2", "option 3"];
select.onblur = function(){
select.options[select.selectedIndex].innerHTML = titlesBlur[select.selectedIndex];
}

关于javascript - 如何为焦点和焦点 Javascript 的 <option> 设置不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42044025/

相关文章:

javascript - ExtJS 在新选项卡中显示链接

javascript - 什么时候是从 html 标签中删除 no-js 类的最佳时机

html - 从 <select> 元素中删除下拉箭头?

javascript - Canvas 获取填充区域的百分比

javascript - 在 phpbb 中按提交后网站无法连接

javascript - Angular Js ng-repeat无法使用ajax从json数组获取输出

css - 在基于 webkit 的浏览器中为特定 <select> 选项设置样式的纯 CSS 解决方案?

javascript - 如何迭代一系列问题和答案

html - Internet Explorer 降低元素内具有奇数高度的文本

javascript - 在 html select 上设置选定值而不使用 runat=server