我有一张大表,其中包含行号和价格。我希望能够通过使用行号查找价格。
function buildtable(){
var tableObj = document.getElementById( 'table' );
var allTRs = tableObj.getElementsByTagName( 'tr' );
for ( var trCounter = 0; trCounter < allTRs.length; trCounter++ )
{
var tmpArr = [];
var allTDsInTR = allTRs[ trCounter ].getElementsByTagName( 'td' );
for ( var tdCounter = 0; tdCounter < allTDsInTR.length - 1; tdCounter++ )
{
tmpArr.push( allTDsInTR[ tdCounter ].innerHTML );
}
arr.push( tmpArr );
}
}
以下代码创建一个列表列表。
如何更改功能,以便其创建单个密钥对存储?
HTML FOR TABLE
foreach($ res as $ row){
$seat = $row['RowNumber'];
$price = $row['Zone.PriceMultiplier * 15.00'];
echo "<tr>";
echo "<td>".$seat."</td>";
echo "<td>".$price."</td>";
echo "<td><input type='checkbox' name='check_list[]' value=\"$seat;\" onclick='javatest(this);' </td>";
echo "</tr>";
}
答案 0 :(得分:2)
您可以将一个对象用作键值映射(哈希表)。
function buildtable() {
var tableObj = document.getElementById('table');
var map = {};
var allTRs = tableObj.getElementsByTagName('tr');
for (var trCounter = 1; trCounter < allTRs.length; trCounter++) {
var tmpArr = [];
var allTDsInTR = allTRs[trCounter].getElementsByTagName('td');
if (allTDsInTR.length) {
map[allTDsInTR[0].innerHTML.trim()] = parseFloat(allTDsInTR[1].innerHTML.trim());
}
}
console.log(map);
}
buildtable();
<table id='table'>
<thead>
<tr>
<td>
RowNumber
</td>
<td>
Price
</td>
<tr>
</thead>
<tbody>
<tr>
<td>
U01
</td>
<td>
24.5
</td>
<tr>
<tr>
<td>
U02
</td>
<td>
22
</td>
<tr>
</tbody>
</table>
结果将类似于:
{
"U01": 24.5,
"U02": 22
}
答案 1 :(得分:0)
像这样吗?
var tableRows = Array.from(document.querySelectorAll('#myTable > tbody > tr'));
var result = {};
tableRows.forEach(row => {
var cols = Array.from(row.getElementsByTagName('td'));
var key = cols[0].innerHTML;
var value = cols[1].innerHTML;
if (!result[key]) {
result[key] = [value];
} else {
result[key].push(value);
}
});
console.log(result);
<table id="myTable">
<thead>
<tr>
<th>RowNumber</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>U01</td>
<td>26.999999284744263</td>
</tr>
<tr>
<td>U02</td>
<td>26.999999284744263</td>
</tr>
<tr>
<td>U01</td>
<td>26.999999284744263</td>
</tr>
</tbody>
</table>