我正在尝试从JSON渲染选择列表。它工作正常,但当我尝试添加if以获得所选它失败。如果所选ID等于预定义的数字,则将select = select写入数组。
我收到的错误消息是“意外令牌if”
var xmlhttp = new XMLHttpRequest();
var url = "roller.json";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
defRolle = 6;
solSelect ="selected=selected";
var arr = JSON.parse(response);
var i;
var out = "<select>";
for(i = 0; i < arr.length; i++) {
out += "<option value='"+
arr[i].RolleID +
"'" + if (arr[i].RolleID===defRolle) {return solSelect} +
" name='"+
arr[i].RolleNavn +
"'>" +
arr[i].RolleNavn +
"</option>";
}
out += "</Select>";
document.getElementById("endreRolle").innerHTML = out;
}
答案 0 :(得分:0)
试试这个
用三元运算符替换if条件,简短明了
var xmlhttp = new XMLHttpRequest();
var url = "roller.json";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
defRolle = 6;
solSelect ="selected=selected";
var arr = JSON.parse(response);
var i;
var out = "<select>";
for(i = 0; i < arr.length; i++) {
out += "<option value='"+
arr[i].RolleID +
"'" + (arr[i].RolleID===defRolle ? solSelect : '') +
" name='"+
arr[i].RolleNavn +
"'>" +
arr[i].RolleNavn +
"</option>";
}
out += "</Select>";
document.getElementById("endreRolle").innerHTML = out;
}
答案 1 :(得分:0)
尝试以下
function myFunction(response) {
defRolle = 6;
solSelect = "selected=selected";
var arr = JSON.parse(response);
var i;
var out = "<select>";
for (i = 0; i < arr.length; i++) {
out += '<option value="' + (arr[i].RolleID === defRolle ? solSelect : "") + '" name="' + arr[i].RolleNavn + '">' + arr[i].RolleNavn + '</option>';
}
out += "</Select>";
document.getElementById("endreRolle").innerHTML = out;
}