jquery - 如何使用 .each jQuery 获取 id 并为每个 jQuery 设置属性?
问题描述
我希望能够获取每个的 id<th>
并将它们设置为每个<td>
表的数据属性。
前:
<table>
<tr>
<th id="1"><th>
<th id="2"><th>
</tr>
<tr>
<td><td>
<td><td>
</tr>
<tr>
<td><td>
<td><td>
</tr>
...
</table>
后:
<table>
<tr>
<th id="1"><th>
<th id="2"><th>
</tr>
<tr>
<td data="1"><td>
<td data="2"><td>
</tr>
<tr>
<td data="1"><td>
<td data="2"><td>
</tr>
...
</table>
到目前为止,我有这个 jQuery :
array = $('table th').map(function(){
return this.id;
});
i = 0;
$('table tr td').each(function() {
$(this).attr('data-title', array[i]);
i++;
});
但它根本不起作用。
有任何想法吗?
解决方案
问题是这$('table tr td')
将返回所有 tds,所以如果你有 2 行 4 个 tds,结果是 8 个 tds,并且 8 比你的计数大。您必须遍历每一行。
//loop over each row
$('table tr').each(function() {
//use the index of the td in the row for the array
$(this).find('td').each(function(index){
$(this).attr('data-title', array[index]);
});
});
//or as an alternative
array.each(function(index, id){
$('table tr td:nth-child('+ (index + 1) +')').attr('data-title', id);
});
推荐阅读
- javascript - Angularjs将json响应合并为一个
- typescript - 将 JSON 文件的输出保存在 Map Object Angular 6 中
- ios - 如何使用 DeviceCheck API swift 获取唯一 ID?
- ionic-framework - 我们如何使用 Appium 处理 Selenium 中的数字签名
- php - LearnPress 为课程内容创建模板 - 不同的流程
- javascript - 没有为键 X 定义路由 - 两个 StackNavigators
- java - JavaFX 场景生成器的奇怪屏幕尺寸
- oracle - oracle如何查找修改用户密码的人
- ruby-on-rails - RSpec:如何编写单元测试用例以接收在私有方法中引发的异常
- java - Java Spring中的单例bean并发