分解单元格合并的行
for (let i = td_row.rowIndex + 1; i < td_row.rowIndex + init_rowspan; i++) { // 向下一行开始插入td
// 计算插入位置,
let in_index
for (let a = 0; a < tb.rows[i].cells.length; a++) {
const td_rc = JSON.parse(tb.rows[i].cells[a].getAttribute('td_rc') as string)
if(td_rc && td_rc.maxc == init_col - 1){ // init_col 单元格的 实际列号,非index
in_index = tb.rows[i].cells[a].cellIndex +1
if (i == 4) { console.log('第4行 所有 td',tb.rows[i].cells)}
// 看控制台打印, 问题在这 行,得到index 为2 的 td, 而不是index 1 的 td
if (i == 4) { console.log('第4行 cells[1]元素',tb.rows[i].cells[1])} // 这是啥原因造成的?
if (i == 4) { console.log('第4行 cells[1]元素的 index',tb.rows[i].cells[1].cellIndex)}
break
}else if(td_rc && td_rc.c == init_maxc + 1){
in_index = tb.rows[i].cells[a].cellIndex
break
}
}
nextTick(() => {
// console.log('3运行到这了',i, in_index)
new_td = tb.rows[i].insertCell(in_index)
new_td.setAttribute('td_rc', `{"r":${i},"c":${in_index},"maxc":${in_index},"maxr":${i}}`)
new_td.innerText = '新行'
})
}
}
另外控制台,两个 length 也不一样,一个4 一个5
这个是因为你用console.log()输出整个对象
console.log()输出对象或数组时是在控制台显示一个对象或数组的引用。
在用console.log()输出数组或对象时,对象(数组)的属性是折叠不显示的。
如果你在console.log()输出之后改变了对象(数组)的属性,当你点击三角展开属性时,会重新读取对象(数组)当前的属性,也就是显示出来的是你点击三角展开时的属性,而不是执行console.log()时的属性。
你用console.log(JSON.stringify(arr));以字符串方式输出就可以看到对象当前的值
tb.rows[i].cells是HTMLCollection
为对象,打印对象到控制台,展开(就是点击前面的下拉箭头看数据项)
时是这个对象的最终状态
(包含后续添加到此HTMLCollection的项),对应题主nextTick中的插入语句
new_td = tb.rows[i].insertCell(in_index)`
目测in_index参数为1,插入在原来的第二项(下标1)前面,这样第二项变为了第三项,看td_rc属性值就知道,因为td_rc没有更改。
用Array.from将HTMLCollection转为另外的dom数组,打印这个数组时,和tb.rows[i].cells分离就不会相互影响了。但是修改了数组中的项时还是会相互影响,因为是td,对象
if (td_rc && td_rc.maxc == init_col - 1) { // init_col 单元格的 实际列号,非index
in_index = tb.rows[i].cells[a].cellIndex + 1var tds = Array.from(tb.rows[i].cells)
if (i == 4) { console.log('第4行 所有 td',tds
) }
// 看控制台打印, 问题在这 行,得到index 为2 的 td, 而不是index 1 的 td
if (i == 4) { console.log('第4行 cells[1]元素',tds[1]
) } // 这是啥原因造成的?
if (i == 4) { console.log('第4行 cells[1]元素的 index', tds[1].cellIndex
) }
break
}
问题在于
if (i == 4) { console.log('第4行 cells[1]元素',tb.rows[i].cells[1])} // 这是啥原因造成的?
if (i == 4) { console.log('第4行 cells[1]元素的 index',tb.rows[i].cells[1].cellIndex)}
你这部分
你改成
if(i == 4 && a==1){
console.log('第4行 cells[1]元素',tb.rows[i].cells[a]);
console.log('第4行 cells[1]元素的 index',tb.rows[i].cells[a].cellIndex)
}
这样改,赢就就解决问题了,因为你只是输出第4行 cells[1]的值,那么也就是i == 4 && a==1 要同时成立下输出
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!