javascript - jQuery 每个循环仅适用于第一次
问题描述
我有 2 divs
,每个 div 都有另一个 div (用于标签),然后是值。
我希望这些标签也添加到项目的左侧。
https://jsfiddle.net/eavbLgnq/
当前的 HTML 输出:
ID
Name
4343
Alpha
657
Team
Age
Job
23
Teacher
44
Coder
期望的结果:
ID
Name
ID 4343
Name Alpha
ID 657
Name Team
Age
Job
Age 23
Job Teacher
Age 44
Job Coder
我得到了什么:
ID
Name
ID 4343
Name Alpha
ID 657
Name Team
Age
Job
ID 23
Name Teacher
ID 44
Name Coder
jQuery代码:
let pu_cells = []
let table_ = $('.pu')
table_.each(function(){
let this_pu = $(this)
this_pu.find(".pu-row_0 .pu-pk-cell").each(function(){
pu_cells.push($(this).text())
})
this_pu.find('.pu-row:not(.pu-row_0)').each(function(i){
$(this).find('.pu-pk-cell').each(function(j){
$(this).html('<span class="pu-cell-label"> '+pu_cells[j]+'</span> ' + $(this).text())
})
})
})
解决方案
你永远不会重置它的值,pu_cells
第二个div
它也有第一个单元格值(ID,Name
我的意思是)。
所以只需放入let pu_cells = []
每个循环。
let table_ = $('.pu')
table_.each(function () {
let pu_cells = []
let this_pu = $(this)
this_pu.find(".pu-row_0 .pu-pk-cell").each(function () {
pu_cells.push($(this).text())
})
this_pu.find('.pu-row:not(.pu-row_0)').each(function (i) {
$(this).find('.pu-pk-cell').each(function (j) {
$(this).html('<span class="pu-cell-label"> ' + pu_cells[j] + '</span> ' + $(this).text())
})
})
})
.pu-cell-label {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="pu pu_0">
<div>
<div>
<div class="pu-row pu-row_0">
<div>
<div>
<div class="pu-pk-cell">ID</div>
<div class="pu-pk-cell">Name</div>
</div>
</div>
</div>
<div class="pu-row pu-row_1">
<div>
<div>
<div class="pu-pk-cell">4343</div>
<div class="pu-pk-cell">Alpha</div>
</div>
</div>
</div>
<div class="pu-row pu-row_2">
<div>
<div>
<div class="pu-pk-cell">657</div>
<div class="pu-pk-cell">Team</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="pu pu_1">
<div>
<div>
<div class="pu-row pu-row_0">
<div>
<div>
<div class="pu-pk-cell">Age</div>
<div class="pu-pk-cell">Job</div>
</div>
</div>
</div>
<div class="pu-row pu-row_1">
<div>
<div class="pu-da-row">
<div class="pu-pk-cell">23</div>
<div class="pu-pk-cell">Teacher</div>
</div>
</div>
</div>
<div class="pu-row pu-row_2">
<div>
<div>
<div class="pu-pk-cell">44</div>
<div class="pu-pk-cell">Coder</div>
</div>
</div>
</div>
</div>
</div>
</div>
推荐阅读
- java - 给定一组数据,检查它是否是二叉搜索树?
- c# - 剑道网格客户端模板输入隐藏字段单击后变为可编辑
- typo3 - 将变量传递给包含 tx_news 插件的内容对象
- python - 如果满足特定条件,则将字符串与列表列表连接
- heroku - Heroku 不会运行他们的示例 sinatra 应用程序,错误是 bundler: failed to load command: rackup
- docker - 使用 kerberose(GSSAPI)SASL 设置设置 kafka 代理的最佳方法是什么?
- typescript - 打字稿地图键自动完成
- r - 打开在单独选项卡中选择的行
- parse-platform - beforeSave 不修改 request.object
- javascript - 如何在每个刷新页面上重置整数计数器