我使用ajax响应创建了一个简单的表。这里我得到的approvedOn
和approvedBy
为null
。
< br/>但我不想将其显示为 null
。我想将其显示为 pending
。有什么建议吗?
var leaveList = [{
"appliedOn": "12-02-2017",
"levType": "causual",
"leaveOn": "12-02-2017",
"duration": "5 days",
"status": "approved",
"approvedOn": "null",
"approvedBy": "null"
}, {
"appliedOn": "12-02-2017",
"levType": "privileged",
"leaveOn": "14-03-2017",
"duration": "8 days",
"status": "pending",
"approvedOn": "13-02-2017",
"approvedBy": "HR"
}];
$(document).ready(function() {
leaveTable()
});
function leaveTable() {
for (var i = 0; i < leaveList.length; i++) {
var tab = '<tr id="' + i + '"><td>' + (i + 1) + '</td><td class="appliedOn">' + leaveList[i].appliedOn + '</td><td class="levType" >' + leaveList[i].levType + '</td><td class="leaveOn" >' + leaveList[i].leaveOn + '</td><td class="duration">' + leaveList[i].duration + '</td><td class="status">' + leaveList[i].status + '</td><td class="approvedOn">' + leaveList[i].approvedOn + '</td><td class="approvedBy">' + leaveList[i].approvedBy + '</td><tr>';
$('#levListTable').append(tab)
}
}
最佳答案
要从收到的对象中获得所需的结果,您可以使用逻辑 OR 运算符 (||
) 来根据需要合并 null
值。另请注意,您显示的代码与您在控制台中显示的对象的图像具有不同的属性名称。确保您使用的名称正确,因为 JS 区分大小写。试试这个:
(leaveList[i].approvedOn || 'pending')
var leaveList = [{
"appliedOn": "12-02-2017",
"levType": "causual",
"leaveOn": "12-02-2017",
"duration": "5 days",
"status": "approved",
"approvedOn": null,
"approvedBy": null
}, {
"appliedOn": "12-02-2017",
"levType": "privileged",
"leaveOn": "14-03-2017",
"duration": "8 days",
"status": "pending",
"approvedOn": "13-02-2017",
"approvedBy": "HR"
}];
$(document).ready(function() {
leaveTable()
});
function leaveTable() {
for (var i = 0; i < leaveList.length; i++) {
var tab = '<tr id="' + i + '"><td>' + (i + 1) + '</td><td class="appliedOn">' + leaveList[i].appliedOn + '</td><td class="levType" >' + leaveList[i].levType + '</td><td class="leaveOn" >' + leaveList[i].leaveOn + '</td><td class="duration">' + leaveList[i].duration + '</td><td class="status">' + leaveList[i].status + '</td><td class="approvedOn">' + (leaveList[i].approvedOn || 'pending') + '</td><td class="approvedBy">' + (leaveList[i].approvedBy || 'pending') + '</td><tr>';
$('#levListTable').append(tab)
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<table class="table table-hover table-bordered">
<thead class="colorBlue">
<tr>
<td>S.No</td>
<td>Applied On</td>
<td>Leave Type</td>
<td>Leave On</td>
<td>Duration</td>
<td>Status</td>
<td>Approved On</td>
<td>Approved By</td>
</tr>
</thead>
<tbody id="levListTable"></tbody>
</table>
关于jquery - 当ajax响应为空时显示一条消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43512067/