如何为循环生成的HTML标签添加指定data-label属性
给表格TD添加指定data-label属性的解决方案
方案一:模板层面直接修改(优先推荐)
如果你的模板引擎支持循环索引,直接修改模板代码就能满足需求,这是最高效的方式:
<#loop:main_tlds_price_add#> <tr> <td data-label="tld" id="<#tag:main_tlds_price_add[].classkey /#>"> .<#tag:main_tlds_price_add[].name /#> </td> <#loop:main_tlds_price_add[].price as index, price#> <td data-label="<#if index == 0#>1 year<#elif index ==1#>2 years<#elif index ==2#>5 years<#/#>"> <#tag:price /#></td> <#/loop:main_tlds_price_add[].price#> </tr> <#/loop:main_tlds_price_add#>
修改说明:
- 把第一个TD的
data-label直接从"Domains"改为"tld" - 价格循环时通过索引判断,给每个价格TD匹配对应的年份标签(1年/2年/5年)
方案二:JS层面处理(模板无法修改时使用)
如果模板引擎不支持索引判断,可在DOM渲染完成后用Underscore.js+原生JS批量修改:
// 等待页面DOM渲染完成后执行 document.addEventListener('DOMContentLoaded', function() { // 获取所有目标表格行 const rows = document.querySelectorAll('tr'); _.each(rows, function(row) { const tds = row.querySelectorAll('td'); // 给第一个TD设置tld标签 tds[0].setAttribute('data-label', 'tld'); // 定义价格对应的标签数组 const priceLabels = ['1 year', '2 years', '5 years']; // 遍历从第二个开始的TD,设置对应标签 _.each(_.slice(tds, 1), function(td, idx) { if (priceLabels[idx]) { td.setAttribute('data-label', priceLabels[idx]); } }); }); });
说明:
- 用Underscore的
each方法遍历行和单元格,保证和现有技术栈兼容 - 逻辑简单直接:先处理域名TD,再按顺序给价格TD匹配预设标签
内容的提问来源于stack exchange,提问作者adeguk Loggcity
相关产品推荐
相关产品推荐

