我有这个代码:
https://jsfiddle.net/eur59yfa/6/
-Html 和 JS
<body>
<table>
<tr>
<td class="first">100</td>
<td class="second">20</td>
</tr>
</table>
<script>
document.body.onload = function(){
var firstTdVal = document.getElementsByClassName('first')[0].innerHTML;
var secondTdVal = document.getElementsByClassName('second')[0].innerHTML;
var valueToBeShown = parseInt(firstTdVal)/parseInt(secondTdVal);
document.getElementsByClassName('second')[0].innerHTML = valueToBeShown ;
}
</script>
</body>
代码运行良好,但我有一个问题。例如,会有其他 td 具有“.third”类、“.fourth”...具有不同的值:240,451...并且所有这些类都必须分为类“.second”。每个结果应显示在自己的 td 中。如何做到这一点,同时保持代码复杂性?
最佳答案
可能超出您的需要,但这展示了如何迭代数组、创建动态元素(并填充它们)以及如何动态分配类和管理新创建元素的 CSS。祝你好运。
let thead = document.querySelector('table thead tr');
let rows = document.querySelectorAll('tbody tr');
let dividends = ['first', 'third', 'fourth'];
// Dynamically Create Table Headers
dividends.forEach(x => {
let new_th = document.createElement('th');
// capitalize the class to use in the table header
let title = x.replace(/\b([a-z])/g, (s) => {
return s.toUpperCase()
});
// prepend "result-" to the class (e.g., "result-first")
new_th.className = `result-${x}`;
new_th.appendChild(document.createTextNode(`${title} Result`));
thead.appendChild(new_th);
});
// Dynamically Generate Result Values (and new table data cells)
Array.prototype.forEach.call(rows, function(row, index) {
let divisor = +row.querySelector('.second').textContent;
dividends.forEach(handle => {
let dividend = +row.querySelector(`.${handle}`).textContent;
let quotient = dividend / divisor;
let new_cell = document.createElement('td');
// append "-value" to the class (e.g., "first-value")
new_cell.className = `${handle}-value`;
new_cell.appendChild(document.createTextNode(quotient)); // add value
row.appendChild(new_cell);
});
});
/* superfluous table styling */
body {
font-size: 16px;
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, "Segoe UI", "Calibri LIght", "Roboto Light", "Roboto", "Lucida Grande", Verdana, Arial, sans-serif;
font-weight: 300;
}
table {
border-collapse: collapse;
border: 1px solid;
}
thead {
border-bottom: 1px solid;
}
td {
border-left: 1px solid;
text-align: left;
}
td,
th {
padding: 4px;
}
/* end page + table styling */
/* demonstrates how to grab the first part of the class name */
[class^=result-] {
color: #09c;
}
/* demonstrates how to grab the last part of the class name */
[class$=-value] {
color: #900;
text-align: right;
}
<table>
<thead>
<tr>
<th>First</th>
<th>Second</th>
<th>Third</th>
<th>Fourth</th>
</tr>
</thead>
<tbody>
<tr>
<td class="first">100</td>
<td class="second">10</td>
<td class="third">300</td>
<td class="fourth">400</td>
</tr>
<tr>
<td class="first">1000</td>
<td class="second">10</td>
<td class="third">3000</td>
<td class="fourth">4000</td>
</tr>
</tbody>
</table>
关于javascript - 多个元素具有相同的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41914860/