如何使用jQuery将文本附加到选择选项文本的末尾?

时间:2017-04-17 02:34:35

标签: jquery

假设我有以下HTML:

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

在这种情况下,我想将General更改为General (current)。选项文本也是动态的。我只想在选项文本的末尾添加(current)

我该怎么做?

提前致谢

4 个答案:

答案 0 :(得分:1)

这是一种方式

&#13;
&#13;
$("#dept option[value='1']").append(' (current)');
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

这个怎么样?

&#13;
&#13;
var current_text = $("#dept :selected").text();
$("#dept :selected").text(current_text + " (current)");
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

这对@LGSon的原始答案略有改进。此版本确保“当前”始终附加到当前选定的选项(我假设选择更改时“值”属性保持不变):

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

答案 3 :(得分:0)

&#13;
&#13;
$('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);
});
&#13;
<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>
&#13;
&#13;
&#13;

相关问题