我正在构建一个选择下拉菜单,其功能如下:
$.each(data,function(key, value) {
$select.append('<option value=' + key + '>' + value + '</option>');
});
这里我复制了我的原始数据样本:
231:"Building"
232:"Trusting"
234:"Engineering"
235:"(*)Monitoring"
236:"Managing"
构建它时,我想:
感谢您的帮助!
答案 0 :(得分:0)
您可以使用.find
确定字符串是否以'(*)'
开头,然后将selected
添加到选项的末尾,并使用切片删除'(*)'
。< / p>
data = {
231:"Building",
232:"Trusting",
234:"Engineering",
235:"(*)Monitoring",
236:"Managing"
}
$select = $("#select");
from = '(*)';
$.each(data,function(key, value) {
if (value.indexOf(from) == 0) {
$select.append('<option value=' + key + ' selected>' + value.slice(from.length) + '</option>');
} else {
$select.append('<option value=' + key + '>' + value + '</option>');
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select"></select>
&#13;