js怎么将html表格数据转为集合
发布网友
发布时间:2022-04-23 03:41
我来回答
共2个回答
热心网友
时间:2022-04-23 05:10
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>demo</title>
<style type="text/css">
table {
display: table;
border-collapse: collapse;
border: 1px solid #ccc;
}
tr, td, th {
border: 1px solid #ccc;
}
input {
min-width: 100px;
}
.operator {
margin: 20px 0;
}
button {
background: white;
font-size: 16px;
}
tr, td, th, input, button {
padding: 6px 12px;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>名称</th>
<th>年龄</th>
<th>描述</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div class="operator">
<button type="button" name="add">设置</button>
<button type="button" name="get" disabled>获取</button>
</div>
</body>
<script type="text/javascript">
var $ = function (selector, context) {
return (context || document).querySelector(selector);
};
var $$ = function (selector, context) {
return (context || document).querySelectorAll(selector);
};
function createTd(name) {
var td = document.createElement('td');
var input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('name', name);
input.setAttribute('value', name + Math.floor(Math.random() * 100 + 1));
td.appendChild(input);
return td;
}
function addRows(len) {
var fg = document.createDocumentFragment();
while (len-- > 0) {
var tr = document.createElement('tr');
tr.appendChild(createTd('name'));
tr.appendChild(createTd('age'));
tr.appendChild(createTd('desc'));
fg.appendChild(tr);
}
$('tbody').appendChild(fg);
}
function getRows() {
var rows = [].slice.call($$('tbody>tr'));
return rows.map(function (tr) {
return {
name: $('[name=name]', tr).value,
age : $('[name=age]', tr).value,
desc: $('[name=desc]', tr).value,
};
});
}
$('[name=add]').addEventListener('click', function () {
[].slice.call($$('tbody>tr')).forEach(function (tr) {
$('tbody').removeChild(tr);
});
addRows(10);
$('[name=get]').removeAttribute('disabled');
}, false);
$('[name=get]').addEventListener('click', function () {
console.table(getRows());
}, false);
</script>
</html>
热心网友
时间:2022-04-23 06:28
var list=[]; 集合
var obj={}; 对象
obj.name=name;对象属性
list.push(obj);对象加入集合