javascript jquery 下拉列表框 - 如何在特定索引处设置选项文本(未选中!)

javascript jquery dropdown listbox - How to set option text at specific index (not selected!)

我的问题是,使用javascript/jquery、"How do you change the value of a dropdown option at a specific index that is NOT the selected index?"

我有一个值下拉列表。用户可以 select 一个选项。我有一种方法可以让用户更改 selected 选项的值。该值已更改,一切正常。

这是我的问题:如果用户决定取消,或者更改为列表中的不同值而不将更改保存到数据库,我想撤消值更改。

如果用户 select 编辑了一个不同的选项,我不想更改新 select 编辑的选项的索引。我只想重置用户更改的选项的值。

我试过 .each 方法:

var changedTitle = $('#ddTitle').text();

$("#ddTitle option").each(function() {
  if($(this).text() == changedTitle) {
    $(this).text(savedTitle);            
  }                        
});

我喜欢循环遍历每一个的想法,但我从未见过第二次执行循环并且浏览器永远不会返回。

我试过 .filter 方法:

var changedTitle = $('#ddTitle').text();

$("#ddTitle option").filter(function(index) { return $(this).text() === changedTitle; }).attr('selected', 'selected');

$("#ddTitle option").filter(function() {  
    return $(this).text() === changedTitle;
}).prop('selected', true);  // changes the selected option

我可以使用上面的过滤器代码,但它设置了 selected 选项。

$("#ddTitle option").filter(function() {  
    return $(this).text() === changedTitle;
}).prop('text', savedTitle);  // execution never returns

我尝试在选项 上使用文本 属性,但是 jquery 变得非常繁忙并且从未执行 returns。

我试过通过文本值查找,这很愚蠢,因为我知道索引:

$("#ddTitle option[value='" + theText + "']").attr('selected', 'selected');

如果这些得到一个选项,它是第一个选项 (0) 或浏览器挂起。

有没有办法在 javascript 或使用 jquery 中以编程方式更改指定索引处的文本值?我试过的都没有用。

要更改第 5 个选项的值,请执行:

$('#yourselect').children('option:eq(4)').html('your text');