You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中使用forloop.counter生成的HTML ID实现复选框联动文本样式

解决方案

这里提供两种适配动态行的实现方案,优先推荐第一种无需依赖ID的方案,兼容性和可维护性更强。

方案1:事件委托实现(适配动态新增行)

无需依赖ID生成规则,后续动态添加表格行也不需要重新绑定事件。

第一步:修改HTML添加类名(方便元素匹配)

{% for item in items %}
<tr>
<td name="product" class="product-name">{{ item.product }}</td>
<td><input type="checkbox" class="product-checkbox"></td>
</tr>
{% endfor %}

第二步:替换原有JavaScript代码

document.addEventListener('click', function(e) {
    // 仅响应产品复选框的点击事件
    if (e.target.classList.contains('product-checkbox')) {
        // 定位到当前复选框所在行的产品名称单元格
        const productCell = e.target.closest('tr').querySelector('.product-name');
        // 切换删除线样式
        productCell.style.textDecoration = e.target.checked ? 'line-through' : 'none';
    }
})

方案2:基于现有动态ID规则实现

如果你不想修改现有HTML结构,可以直接匹配你已生成的checkbox开头的ID实现批量绑定:

document.querySelectorAll('[id^="checkbox"]').forEach(checkbox => {
    checkbox.addEventListener('click', function() {
        // 提取ID中的行号
        const rowNum = this.id.replace('checkbox', '');
        const productCell = document.getElementById(`product${rowNum}`);
        productCell.style.textDecoration = this.checked ? 'line-through' : 'none';
    })
})

注意:该方案仅对页面加载时已存在的行生效,如果后续有动态新增行的需求,新增行需要单独绑定事件。

内容的提问来源于stack exchange,提问作者Nelso

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 16:06:03