【发布时间】:2021-09-01 07:18:38
【问题描述】:
我有一个动态表(从下拉选择中选择的列)从 JSON 中获取数据。表格的列标题是 JSON 数据的一部分。
我正在使用它从 JSON 中捕获列标题,但它以“未定义”的形式出现。
jQuery.each(data, function(k, v) {
html += '<th id="myHeader">' + v.ColHeading + '</th>';
});
他们的数据不会被捕获为列标题,而是作为表格的第一行。我需要的是 'ColHeading' 值以反映为列标题,而 'Height' 和 'Weight' 将成为我表中的第一行和第二行。
JSON 如下:
var StatJSON = {
"Option1": {
"ColHeading": "Volvo",
"Height": "aaa cm",
"Weight": "xxx kg",
},
"Option2": {
"ColHeading": "Mercedes",
"Height": "bbb cm",
"Weight": "yyy kg",
},
"Option3": {
"ColHeading": "Maruti",
"Height": "ccc cm",
"Weight": "zzz kg",
},
};
获取数据入表的jQuery如下:
function PrintTable(data) {
var html = '<table class="compTable"><thead><tr><th>';
if (data && data.length) {
html += '</th>';
jQuery.each(data, function(k, v) {
html += '<th id="myHeader">' + v.ColHeading + '</th>';
});
html += '</tr>';
html += '<tbody>';
jQuery.each(StatJSON[data[0]], function(k, v) {
html += '<tr><td>' + k + '</td>';
jQuery.each(data, function(k2, v2) {
html += '<td>' + StatJSON[data[k2]][k] + '</td>';
});
html += '</tr>';
});
} else { html += 'No results found</td></tr>'; }
html += '</tbody></table>';
return html;
}
找到下面的工作代码:
jQuery(document).ready(function($) {
var StatJSON = {
"Option1": {
"ColHeading": "Volvo",
"Height": "aaa cm",
"Weight": "xxx kg",
},
"Option2": {
"ColHeading": "Mercedes",
"Height": "bbb cm",
"Weight": "yyy kg",
},
"Option3": {
"ColHeading": "Maruti",
"Height": "ccc cm",
"Weight": "zzz kg",
},
};
jQuery('#btnSubmit').click(function() {
var data = [];
jQuery("#selection").find(':selected').each(function(e) {
var this_input = jQuery(this);
if (this_input.is(':selected')) {
data.push(this_input.val());
}
});
$('#divResult').empty().append(PrintTable(data));
function PrintTable(data) {
var html = '<table class="compTable"><thead><tr><th>';
if (data && data.length) {
html += '</th>';
jQuery.each(data, function(k, v) {
html += '<th id="myHeader">' + v.ColHeading + '</th>';
});
html += '</tr>';
html += '<tbody>';
jQuery.each(StatJSON[data[0]], function(k, v) {
html += '<tr><td>' + k + '</td>';
jQuery.each(data, function(k2, v2) {
html += '<td>' + StatJSON[data[k2]][k] + '</td>';
});
html += '</tr>';
});
} else {
html += 'No results found</td></tr>';
}
html += '</tbody></table>';
return html;
}
});
});
body {
font-family: montserratbold, montserratregular, sans-serif;
}
.divResult {
overflow: scroll;
position: relative;
}
.compTable {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
margin: 10px;
border: 1px solid #222;
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<select id="selection" multiple="multiple">
<option value="Option1">Volvo</option>
<option value="Option2">Mercedes</option>
<option value="Option3">Maruti</option>
<br />
<input id="btnSubmit" class="button" type="submit" value="submit" />
</select>
<br /><br />
<div id="divResult" class="divResult"></div>
【问题讨论】: