使用forloop.counter在javascript中创建的HTML id



我有一个表,其中每行都包含一个产品和一个复选框。我现在想根据复选框更改文本装饰。我的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>

您不需要ids来关联复选框和产品,只需使用类并找到与单击的复选框具有相同父级的.product即可。

下面是一个使用事件委派的快速示例,该事件委派应用于监视复选框上的单击的表。它使用closest()访问单击的复选框tr祖先,然后查询具有类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>

最新更新