这可能吗?
我有:
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/