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

时间:2017-02-04 18:33:21

标签: javascript html select option

这可能吗?:

enter image description here

我有:

&#13;
&#13;
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];
}
};
&#13;
<select id="select"></select>
&#13;
&#13;
&#13;

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

<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

3 个答案:

答案 0 :(得分:1)

是的,这是可能的。使用onblur事件http://www.w3schools.com/jsref/event_onblur.asp。这是一个基于你的小提琴的例子:

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

答案 1 :(得分:1)

这样的事情应该有效:

var titles = {
  'opt1 (beginner)' : 'option1',
  'opt2 (intermediate)' : 'option2',
  'opt3 (prof)' : 'option3'
};

var select = document.getElementById('select');

for (var title in titles) {
  var option = document.createElement("option");
  option.textContent = title;
  select.append(option);
}

select.onfocus = function() {
  var i = 0;
  for (var title in titles) {
    select.options[i++].textContent = title;
  }
}

select.onblur = function() {
  select.options[select.selectedIndex].innerHTML = titles[select.value];
}
<select id="select"></select>

答案 2 :(得分:0)

你也可以尝试使用JQuery,如下所示:

<强>的Javascript

var options = [
  {value: '1', off: 'Option 1', on: 'Opt 1'},
  {value: '2', off: 'Option 2', on: 'Opt 2'}];

$(function(){
    var $select = $('#dynamic-select');
    // create options
    $.each(options, function(index, elem) {
        $('<option>').val(elem.value).text(elem.off).appendTo($select);
    });

    $('#dynamic-select').focus(function(){
        // when focused, alternate text to property 'on'
        alternateText('on');
    }).blur(function(){
        // when blur occurs, alternate text to property 'off'
        alternateText('off');
    }).change(function(){ $select.blur();});
});

function alternateText(property) {
    $.each(options, function(index, elem) {
            $('#dynamic-select option:eq(' + (index+1).toString() + ')').text(elem[property]);
    });
};

<强> HTML

<select id="dynamic-select">
    <option selected="selected">choose...</option>
</select>

Working JSFiddle