2017-04-17 96 views
-1

比方说,我有以下HTML:如何使用jQuery将文本附加到选择选项文本的末尾?

<select id="dept"> 
<option value="1" selected>General</option> 
<option value="2">Payment Problems</option> 
</select> 

在这种情况下我想改变GeneralGeneral (current)。选项文本也是动态的。我只想在选项文本的末尾附加(current)

我该怎么做?

在此先感谢

+0

是否总是字'(电流)'不管哪个被选中? – LGSon

+0

是的,我总是希望在选项文本 –

回答

1

这里有一种方法

$("#dept option[value='1']").append(' (current)');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<select id="dept"> 
 
    <option value="1" selected>General</option> 
 
    <option value="2">Payment Problems</option> 
 
</select>

+0

之后加上'(current)'谢谢,因为它使用了jQuery,所以我将它标记为答案。 int11也发布了一个很好的选择,可以在常规JS中使用。 –

+0

@JDel谢谢......是的,他/他做了 – LGSon

1

这个怎么样?

var current_text = $("#dept :selected").text(); 
 
$("#dept :selected").text(current_text + " (current)");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> 
 
<select id="dept"> 
 
<option value="1" selected>General</option> 
 
<option value="2">Payment Problems</option> 
 
</select>

+0

我希望有某种方式可以做'+ =“(current)”'你怎么可以做'document.getElementById(“element”)。在JS中,innerHTML + =“要追加的值”。这不可能吗? –

+0

这样的事情? https://jsfiddle.net/4h2mbnaf/ – int11

+0

这很完美,谢谢! –

0

$('select').change(function(){ 
 
var valu = $(this).val(); 
 
var text = $(this).find('option:selected').text(); 
 
text += ' (current)'; 
 
$(this).find("option:contains('current')").each(function(){ 
 
var txt = $(this).text().replace('(current)','') 
 
$(this).text(txt); 
 
}); 
 
$(this).find('option:selected').text(text); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<select id="dept"> 
 
<option value="1" selected>General</option> 
 
<option value="2">Payment Problems</option> 
 
</select>

1

这是一个轻微的改善由@LGSon原来的答案。该版本可确保“当前”总是附加到当前选定的选项(我认为“值”属性保持不变时,选择更改):

$('#dept option[selected=""]').append(' (Current)'); 
相关问题