我有30个用户,ID为1~30
memberInThisGroup
是一个数组[2,24]
我想检查id是否在数组中(2,24)然后给它选择selected
string +="<option value=\""+data.userId+"\" selected >"+data.userName+"</option>";
否则,只是一个正常选项
string +="<option value=\""+data.userId+"\">"+data.userName+"</option>";
这是我的代码有错误,似乎只是检查了一次,而selected
选项是相反的
请指导我如何写
谢谢
function getCurrentusers(memberInThisGroup,groupId) {
console.log(memberInThisGroup); //2,24
$.ajax({
type : 'GET',
url : 'currentusers',
async : true,
success : function(datas) {
//for loop every elements
var string ="";
for(var i in datas){
var data = datas[i];
if(memberInThisGroup.indexOf(data.userId)){
console.log("We have member"+data.userId);
string +="<option value=\""+data.userId+"\" selected >"+data.userName+"</option>";
}else{
console.log("We don't have member"+data.userId);
string +="<option value=\""+data.userId+"\">"+data.userName+"</option>";
}
}
$("#e_"+groupId).append(string);
$('#e_'+groupId).multiSelect('refresh');
}
});
}
datas
ajax get是json喜欢:
[{"userId":1,"userName":"Ken","password":"a12345","account":"ken@qq.com"},
{"userId":2,"userName":"wen","password":"qqqq","account":"wen@gmail.com"},
{"userId":3,"userName":"win","password":"1234","account":"win@gmail.com"},...]
这是我的控制台输出:
We have member1
We don't have member2
We have member3
We have member4
We have member5
....
但我的期望是:
We have member2
We have member24
We don't have member1
We don't have member3
We don't have member4
We don't have member5
....
答案 0 :(得分:1)
试试这个
var string = "",
memberInThisGroup = [2, 24], // just for test
data, selected;
for (var i = 0, len = datas.length; i < len; i++) {
data = datas[i];
selected = (memberInThisGroup.indexOf(data.userId) >= 0) ? 'selected' : '';
string += "<option value=\"" + data.userId + "\" " + selected + ">" + data.userName + "</option>";
}