2013-02-26 80 views
5

我不確定是否將所有人都與上述標題混淆。我的問題如下。僅在選定模式下更改選定選項的文本

我使用標準的javascript(沒有jQuery)和HTML代碼。要求是對於<select>...</select>菜單,我有一個不同長度的動態列表。

現在如果長度爲option[selectedIndex].text > 43個字符,我想將option[selectecIndex]更改爲新的文本。

我能夠通過調用

this.options[this.selectedIndex].text = "changed text"; 
在onChange事件的正常工作

做到這一點。這裏的問題是用戶決定更改選擇後,下拉列表將顯示帶有更改文本的前面選擇的文本。這需要顯示原始列表。

我很難過!有沒有更簡單的方法來做到這一點?

任何幫助將是偉大的。

感謝

+4

你能建立一個的jsfiddle? – Supplement 2013-02-26 21:16:48

回答

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/

+0

這工作就像我已經有。正如在我選擇讓我們說'選項1'時,只要我選擇它,它就會更改爲「更改文本」,並顯示爲已選中。現在,當我再次點擊下拉菜單時,「選項1」現在以「更改文本」的形式出現。我想始終顯示下拉選項作爲原始列表! – curioussam 2013-02-26 21:34:09

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; 

}); 
+0

問題是我是和不能使用jQuery。正在尋找一種處理該問題的標準JavaScript方式。 – curioussam 2013-02-26 23:23:17

+0

你可以很容易地將它轉換爲標準的JavaScript。插入沒有jQuery的DOM元素只是一個痛苦。 – Mike 2013-02-26 23:26:06

+0

我會盡力的。我不是來自jQuery背景,所以會花費我一些時間來理解和改變。反正謝謝! :) – curioussam 2013-02-26 23:28:21

相關問題