5

我不确定我是否将每个人都与上述标题混淆了。我的问题如下。

我在我的代码中使用标准的 javascript(没有 jQuery)和 HTML。要求是对于<select>...</select>菜单,我有一个不同长度的动态列表。

现在如果option[selectedIndex].text > 43字符的长度,我想将其更改 option[selectecIndex]为新文本。

我可以通过调用来做到这一点

this.options[this.selectedIndex].text = "changed text"; 

在工作正常的 onChange 事件中。这里的问题是,一旦用户决定更改选择,下拉列表将显示带有更改文本的先前选定文本。这需要显示原始列表。

我难住了!有没有更简单的方法来做到这一点?

任何帮助都会很棒。

谢谢

4

2 回答 2

3

您可以将以前的文本值存储在某些数据属性中,并在必要时使用它来重置文本:

document.getElementById('test').onchange = function() {

    var option = this.options[this.selectedIndex];

    option.setAttribute('data-text', option.text);
    option.text = "changed text";

    // Reset texts for all other options but current
    for (var i = this.options.length; i--; ) {
        if (i == this.selectedIndex) continue;
        var text = this.options[i].getAttribute('data-text');
        if (text) this.options[i].text = text;
    }
};

http://jsfiddle.net/kb7CW/

于 2013-02-26T21:25:50.487 回答
2

你可以用 jquery 很简单地做到这一点。这是一个工作小提琴:http: //jsfiddle.net/kb7CW/1/

这里也是它的脚本:

      //check if the changed text option exists, if so, hide it
$("select").on('click', function(){
   if($('option#changed').length > 0)
   {
        $("#changed").hide()
   }
});
//bind on change
$("select").on('change', function(){
    var val = $(":selected").val(); //get the value of the selected item
    var text = $(':selected').html(); //get the text inside the option tag
    $(":selected").removeAttr('selected'); //remove the selected item from the selectedIndex
    if($("#changed").length <1) //if the changed option doesn't exist, create a new option with the text you want it to have (perhaps substring 43 would be right
          $(this).append('<option id="changed" value =' + val + ' selected="selected">Changed Text</option>');
    else
        $('#changed').val(val) //if it already exists, change its value

   $(this).prop('selectedIndex', $("#changed").prop('index')); //set the changed text option to selected;

});
于 2013-02-26T22:58:40.740 回答