我在for循环中遇到if语句时遇到麻烦,其中项目不适合h1下的放置,就像我期望的那样,这几乎就像if第一次被错过了而把事情搞砸了
这是一些示例代码和jsfiddle this
resultat
var jsonOut = [{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535678338,
},
{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535678338,
},
{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535594440,
},
{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535594440,
},
]
var content = ''
var lastDate = 0
for (var i = 0; i < jsonOut.length; i++) {
var testDate = new Date(jsonOut[i].timestamp * 1000);
var contentNow = ''
var ResultName = ''
var h1marker = ''
for (var j = 0; j < jsonOut[i].check.length; j++) {
ResultName = ResultName + '' + jsonOut[i].check[j].name + '<br>'
contentNow = testDate + '<br>' + ResultName
}
if (jsonOut[i].timestamp != lastDate) {
h1marker = "<h1>" + testDate.getDate() + "</h1>"
lastDate = jsonOut[i].timestamp
}
content = h1marker + contentNow + content
}
$("#tests").html(content)
答案 0 :(得分:1)
您的if语句完全没有问题。您在此部分的代码
content = h1marker + contentNow + content
将新内容放在旧内容的前面,因此,每个日期的第二个条目都在标题“ 30”上方。
将其更改为content = content + h1marker + contentNow
,如以下代码片段所示:
var jsonOut = [{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535678338,
},
{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535678338,
},
{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535594440,
},
{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535594440,
},
]
var content = ''
var lastDate = 0
for (var i = 0; i < jsonOut.length; i++) {
var testDate = new Date(jsonOut[i].timestamp * 1000);
var contentNow = ''
var ResultName = ''
var h1marker = ''
for (var j = 0; j < jsonOut[i].check.length; j++) {
ResultName = ResultName + '' + jsonOut[i].check[j].name + '<br>'
contentNow = testDate + '<br>' + ResultName
}
if (jsonOut[i].timestamp != lastDate) {
h1marker = "<h1>" + testDate.getDate() + "</h1>"
lastDate = jsonOut[i].timestamp
}
content = content + h1marker + contentNow
}
$("#tests").html(content)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tests">
</div>