3 回答
TA贡献1963条经验 获得超6个赞
ids 在页面上应该是唯一的,因此getElementById只返回一个元素(如果没有找到匹配的 id,则返回 null),但是您可以在数据集属性的帮助下并使用类而不是 ids 来执行计算函数,如下所示:
function calculate() {
const result = document.querySelector(`#${this.dataset.result}`);
result.value = Number(this.value) * 2;
}
const inputElements = document.querySelectorAll('.fuel');
inputElements.forEach(input => input.addEventListener('change', calculate));
table,
th,
td {
border: 1px solid black;
}
<! --COMIENZO TABLA -->
<table id="MyTable" class="egt">
<! --PRIMERA LINEA -->
<tr>
<th>Fuel</th>
<th>Double_Fuel</th>
</tr>
<! --SEGUNDA LINEA -->
<tr>
<td>
<input type="number" class="fuel" data-result="fuel1">
</td>
<td>
<input type="number" id="fuel1">
</td>
</tr>
<! --TERCERA LINEA -->
<tr>
<td>
<input type="number" class="fuel" data-result="fuel2">
</td>
<td>
<input type="number" id="fuel2">
</td>
</tr>
</table>
TA贡献1804条经验 获得超3个赞
发生这种情况是因为您复制了IDs,这在单个网页上必须是唯一的。
因此,我更改了IDstoclasses并使用了该.querySelectorAll()方法,然后通过forEach循环将该方法添加到您可能拥有的.addEventListener()所有可能(以供将来支持)。<input><table>
这是工作代码:
<html>
<body>
<style> table, th, td {border: 1px solid black;} </style>
<! --COMIENZO TABLA -->
<table id="MyTable" class="egt">
<! --PRIMERA LINEA -->
<tr>
<th>Fuel</th>
<th>Double_Fuel</th>
</tr>
<! --SEGUNDA LINEA -->
<tr>
<td>
<input type="number" class="fuel">
</td>
<td>
<input type="number" class="fuel2" >
</td>
</tr>
<! --TERCERA LINEA -->
<tr>
<td>
<input type="number" class="fuel">
</td>
<td>
<input type="number" class="fuel2" >
</td>
</tr>
</table>
<script>
var fuels = document.querySelectorAll('.fuel');
fuels.forEach(function(elem) {
elem.addEventListener("change", function() {
this.parentElement.nextElementSibling.firstElementChild.value = Number(this.value)*2;
});
});
</script>
</body>
</html>
TA贡献1810条经验 获得超4个赞
你可以这样做:
var fuel = document.getElementById('fuel');
var fuel2 = document.getElementById('fuel2');
function calculate(elem) {
document.getElementById('double-' + elem.target.id).value = Number(elem.target.value) * 2;
}
document.getElementById('fuel').addEventListener('change', calculate);
document.getElementById('fuel2').addEventListener('change', calculate);
table,
th,
td {
border: 1px solid black;
}
<table id="MyTable" class="egt">
<tr>
<th>Fuel</th>
<th>Double_Fuel</th>
</tr>
<tr>
<td>
<input type="number" id="fuel">
</td>
<td>
<input type="number" ID="double-fuel">
</td>
</tr>
<tr>
<td>
<input type="number" id="fuel2">
</td>
<td>
<input type="number" ID="double-fuel2">
</td>
</tr>
</table>
添加回答
举报