我有一個表格,其中每一行都包含一個產品和一個復選框。我現在想根據復選框更改文本裝飾。我的 javascript 代碼有效,但僅在第一行。我意識到我使用的 id 不是唯一的。因此,我添加了一個 forloop.counter 來創建唯一的 ID。但是現在我沒有為我的 javascript 找到處理這些 id 的解決方案。該表始終具有不同數量的行。有沒有人有想法?
提前謝謝了!
我的 HTML 代碼
{% for item in items %}
<tr>
<td name="product" id="product{{ forloop.counter }}">{{ item.product }}</td>
<td><input type="checkbox" id="checkbox{{ forloop.counter }}"></td>
</tr>
{% endfor %}
我的 javascript 包含在 html 中。
<script>
document.getElementById('checkbox').onclick = function() {
document.getElementById('product').style.textDecoration = this.checked ? "line-through" : "none";
};
</script>
uj5u.com熱心網友回復:
您不需要id將復選框和產品關聯起來,您可以簡單地使用類并找到.product與單擊的復選框具有相同父級的 。
這是一個使用事件委托的快速示例,該示例應用于監視復選框的表。它用于closest()訪問單擊的復選框tr祖先,然后查詢具有 class 的子元素product。
document.getElementById('table1').addEventListener('click', function(event) {
if (event.target.type === 'checkbox') {
const product = event.target.closest('tr').querySelector('.product');
product.style.textDecoration = event.target.checked ? "line-through" : "none";
}
});
<table id="table1">
<tr>
<td name="product" class="product">product 1</td>
<td><input type="checkbox" ></td>
</tr>
<tr>
<td name="product" class="product">product 2</td>
<td><input type="checkbox" ></td>
</tr>
<tr>
<td name="product" class="product">product 3</td>
<td><input type="checkbox" ></td>
</tr>
</table>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/367411.html
標籤:javascript html for循环
