【发布时间】:2018-02-15 05:36:34
【问题描述】:
使用生成表格的函数 showResults () 有困难。我想根据键:值数据在“HasPDF”、“HasMobile”或“应用”之间是否为 1 从 3 个图像中选择显示 1 个图像。所以我尝试使用 if-then-else 语句来筛选 3 种可能性。 有什么建议吗?谢谢你。绕来绕去..
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
table {
margin: 3px;
}
table th {
font-weight: bold;
cursor: pointer;
}
table th, table td {
padding: 3px;
border: 1px solid #000;
}
</style>
<script>
var arr = [
{
"Inn_ID": "2292522",
"Event_Name": "Jaguars ",
"Event_Date": "2017-11-19 00:00:00",
"ticket_total": "76.0",
"HasPDF": "1",
"HasMobile": "0",
"apponly": "0"
},
{
"Inn_ID": "2292523",
"Event_Name": "Pelicans",
"Event_Date": "2018-01-16 00:00:00",
"ticket_total": "50.0",
"HasPDF": "0",
"HasMobile": "1",
"apponly": "0"
},
{
"Inn_ID": "2292524",
"Event_Name": "Owls",
"Event_Date": "2018-01-16 00:00:00",
"ticket_total": "60.0",
"HasPDF": "0",
"HasMobile": "0",
"apponly": "1"
}
];
$(function() {
$('#headings th').click(function() {
var id = $(this).attr('id');
var asc = (!$(this).attr('asc')); // switch the order, true if not set
// set asc="asc" when sorted in ascending order
$('#headings th').each(function() {
$(this).removeAttr('asc');
});
if (asc) $(this).attr('asc', 'asc');
sortResults(id, asc);
});
showResults();
});
function sortResults(prop, asc) {
arr = arr.sort(function(a, b) {
if (asc) return (a[prop] > b[prop]);
else return (b[prop] > a[prop]);
});
showResults();
}
function image(thisImg) {
var img = document.createElement("IMG");
img.src = thisImg;
document.getElementById('imageDiv').appendChild(img);
}
function showResults () {
var html = '';
for (var e in arr) {
html += '<tr>'
+'<td>'+arr[e].Event_Date+'</td>'
+'<td><a href="https://www.thexx.com/orders/view-invoice/'+arr[e].Inn_ID+'" target="_blank">'+arr[e].Inn_ID+' </a></td>'
+'<td>'+arr[e].ticket_total+'</td>'
+'<td>'+if (arr[e].HasPDF == "1") {
image('pdf.png');
} else if (arr[e].HasMobile == "1"){
image('mobile.jpeg');
} else {image('link.png');}
+'<div id="imageDiv" style="width=20"></div></td>'
+'</tr>';
}
$('#results').html(html);
}
</script>
</head>
<body>
Click on the table headings to sort the results.
<table>
<thead id="headings">
<tr>
<th id="Event_Date">Event Date</th>
<th id="Inn_ID">Inn ID</th>
<th id="ticket_total">Amount</th>
<th id="order">Order Type</th>
</tr>
</thead>
<tbody id="results">
<!-- this will be auto-populated -->
</tbody>
</table>
</body>
</html>
【问题讨论】:
标签: javascript arrays json html