我有一个JSON,我使用jQuery $.each
函数将数据附加到表中。我做一个if语句来检查一个值是否匹配一个字符串。
在我的上一个表格列中,我需要从另一个文本过滤器中获取数据。因此,如果数据值与我的过滤器匹配,则将其作为最后一个td
dataset = [
"river": {
"year": "2016",
"name": "Silver Creek",
"series": "Caught fish",
"weight": "100 kg",
},
"river": {
"year": "2016",
"name": "Silver Creek",
"series": "Released fish",
"weight": "60 kg"
}
];
$(dataset).each(function(i, data){
if (data.year === "2016" && data.series === "Caught fish") {
$('tbody').append('<tr class="river"><td>' + this.year + '</td><td>' + this.name + </td><td>' + this.weight + </td></tr>')
} if (data.year === "2016" && data.series === "Released fish") {
$('tr.river').append('<td>' + this.weight + '</td>')
}
});
上面的代码没有,但我想要,但可能暗示我想要实现的目标。
我需要作为一个表格行:
YEAR | NAME | CAUGHT | RELEASED
2016 | Silver Creek | 100 kg | 60 kg
有什么建议吗?我可以根据$.each
函数之外的数据集构建一个新变量吗?
答案 0 :(得分:1)
对已发布的鱼使用 :contains 选择器查看表中是否已存在年份和水体:
var dataset = [
{"year": "2015","name": "Cedar Creek","series": "Caught fish","weight": "90 kg"},
{"year": "2016","name": "Silver Creek","series": "Caught fish","weight": "60 kg"},
{"year": "2015","name": "Cedar Creek","series": "Released fish","weight": "40 kg"},
{"year": "2016","name": "Silver Creek","series": "Released fish","weight": "60 kg"}
];
dataset.forEach(function(data) {
if(data.series === 'Caught fish') {
$('tbody').append('<tr class="river"><td>' + data.year + '<td>' + data.name + '<td>' + data.weight);
} else {
$('tr:contains(' + (data.year + data.name) + ')').append('<td>' + data.weight);
}
});
tr > * {border: 1px solid #ddd;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr><th>YEAR<th>NAME<th>CAUGHT<th>RELEASED
</table>