gpt4 book ai didi

javascript - 带有单选按钮的 JSON 到 Html 表

转载 作者:行者123 更新时间:2023-11-30 09:11:02 25 4
gpt4 key购买 nike

我有一个 JSON 数据,其中 Gender : 1 表示Male,Gender : 2 表示Female。我想将它们转换为 3 行的 rowspan 内 html 表 内的单选按钮。

比方说,对象的 JS 数组是:

var data = 
[{
"Gender": 1,
"Height": [0,0,0],
"Book": 3
},
{
"Gender": 2,
"Height": [0,0,0],
"Book": 4
}];

How do I convert this JSON data to a html table like this with checked radio buttons?

enter image description here

最佳答案

希望对你有帮助

var tbody = document.querySelector('#table tbody');
var data =
[{
"Gender": 1,
"Height": [0,0,0],
"Book": 3
},
{
"Gender": 2,
"Height": [0,0,0],
"Book": 4
}];


for (var i = 0; i < data.length; i++) {
for (var j = 0; j < 3; j++) {
var row = document.createElement('tr');
if (j === 0) {
if (data[i].hasOwnProperty('Gender')) {
row.appendChild(createGenderRadioCell(data[i]['Gender']))
}
}
if (data[i].hasOwnProperty('Height')) {
row.appendChild(createHeightCells(data[i]['Height'][j]))
}
if (j === 0) {
if (data[i].hasOwnProperty('Book')) {
row.appendChild(createBookCell(data[i]['Book']))
}
}
tbody.appendChild(row);
}
}


function createGenderRadioCell(gender) {
var cell = document.createElement('td');
cell.setAttribute('rowspan', 3);

var male = document.createElement('input'),
female = document.createElement('input');
var malelabel = document.createElement('label'),
femalelabel = document.createElement('label');

male.name = 'gender' + i;
male.type = 'radio';
male.value = 1;
if (gender ===1) {
male.setAttribute('checked', '');
}

malelabel.appendChild(male);
malelabel.innerHTML = malelabel.innerHTML + 'Male';
female.name = 'gender' + i;
female.type = 'radio';
female.value = 2;
if (gender=== 2) {
female.setAttribute('checked', '')
}
femalelabel.appendChild(female);
femalelabel.innerHTML = femalelabel.innerHTML + 'Female';
cell.appendChild(malelabel);
cell.appendChild(femalelabel);
return cell;
}
function createHeightCells(val) {
var cell = document.createElement('td');
cell.innerHTML = val;
return cell;
}

function createBookCell(val) {
var cell = document.createElement('td');
cell.innerHTML = val;
cell.setAttribute('rowspan', 3);
return cell;
}
#table {
border: 1px solid black;
border-collapse: separate;
border-spacing: 2px;
}

#table td, #table th {
border: 1px solid black;
}
<table id="table">
<thead>
<tr>
<th>
Gender
</th>
<th>
Height
</th>
<th>
Book
</th>
</tr>
</thead>
<tbody>

</tbody>
</table>

关于javascript - 带有单选按钮的 JSON 到 Html 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59021734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com