2 回答
TA贡献1780条经验 获得超5个赞
假设您的 HTML 正文中只有此表...
let t = document.getElementsByTagName("table");
let trs = t[0].getElementsByTagName("tr");
let oKeys = [], oVals = [];
let ths = trs[0].getElementsByTagName("th");
let tds = trs[1].getElementsByTagName("td");
ths = Array.from(ths);
tds = Array.from(tds);
ths.map( item => {
oKeys.push(item.innerText);
return ;
});
tds.map( item => {
oVals.push(item.innerText);
return ;
});
console.log("O keys ", oKeys);
console.log("oVals ", oVals);
let newObj = {};
oKeys.map( (key, i) => {
let val = oVals[i];
Object.assign(newObj, {[key] : val })
});
console.log(newObj);
<table id="myTable">
<tbody>
<tr>
<th>Role</th>
<th>Device Name</th>
<th>IP Address </th>
<th>MAC Address </th>
<th>Registered </th>
<th>Subscribers </th>
<th>Events </th>
</tr>
<tr>
<td>
CM
</td>
<td>
-
</td>
<td>192.168.7.110 </td>
<td>506182488323 </td>
<td>XYZ
</td>
<td> Shkdsd30ec1
</td>
<td>Events
</td>
</tr>
</tbody>
</table>
newObj 保存您想要的数据。您可以在上述逻辑中添加更多内容。
TA贡献1827条经验 获得超7个赞
使用 jQuery 进行 dom 选择,这段 JS 代码应该可以工作
var myRows = [];
var headersText = [];
var $headers = $("th");
// Loop through grabbing everything
var $rows = $("tbody tr").each(function(index) {
$cells = $(this).find("td");
myRows[index] = {};
$cells.each(function(cellIndex) {
// Set the header text
if(headersText[cellIndex] === undefined) {
headersText[cellIndex] = $($headers[cellIndex]).text();
}
// Update the row object with the header/cell combo
myRows[index][headersText[cellIndex]] = $(this).text();
});
});
// Let's put this in the object like you want and convert to JSON (Note: jQuery will also do this for you on the Ajax request)
var myObj = {
"myrows": myRows
};
console.log(myRows);
- 2 回答
- 0 关注
- 126 浏览
添加回答
举报