javascript - 指定后添加行
问题描述
基本上我有一个表,用户可以添加行。根据行类型,它们的添加方式略有不同。标准行始终由 .append() 添加,但应始终在创建或修改的最后一行之后添加“指令”行。
//Lastrow is always a Jquery object of a table row that's present on the DOM.
//The variable is set/reset whenever a row is created or modified.
lastRow = $(row)
...
//indexRow = lastRow, but passed as an argument.
function addRow(rowType, indexRow){
newRow="<tr><td>Test</td></tr>";
//Want to add the new row after the last created row, and it doesn't work.
//However if lastRow is an existing row that's been modified, it does work.
if(rowType =='instructionRow'){
indexRow.after($(newRow));
indexRow.get(0).scrollIntoView();
}
if(rowType=="normalRow"){
$('tableId').append(newRow);
lastRow = $(newRow);
}
}
lastRow 设置位置的一些示例
//In the add row function itself, if the row is not an instruction row.
//Where newRow = HTML for a table row
//This does not work when you try addRow("instructionRow", lastAddedRow) after it
if(rowType=="normalRow"){
lastRow = $(newRow);
}
//In a row that is updated.
//Where row is a row in the dom, in a .each() loop
//In this case, the addRow("instructionRow", lastRow) will work.
$('tableId tr').each(function (index, row){
if(row.childNodes[1].innerText == 'whatever'){
lastRow = $(row);
row.childNodes[1].innerText = "New Value";
}
所以我可以确定新创建的行在添加到 lastRow 时不是活动的 dom 元素,但不知道为什么或如何解决它。
编辑:小提琴: https ://codepen.io/josh-dredge/pen/ZEppyXm?editors=1111
复制。
- 按“添加普通行”。两三遍。
- 按“添加指令行”。什么都不会发生(它的意思是)
- 按“更新普通行”。第一个正常行将更新。4 按“添加指令行”。现在将在更新的普通行之后添加一个指令行
解决方案
由于您的变量newRow
是一个字符串,因此当您执行以下操作时:
$('#tableId').append(newRow);
lastRow = $(newRow);
它不是同一个“newRow”——第二行通过重新解析字符串来创建一个新元素(尚未附加到 DOM)。
相反,您可以这样做:
lastRow = $(newRow);
$('#tableId').append(lastRow);
或者
lastRow = $(newRow).appendTo('#tableId')
两者都将设置lastRow
为已附加且位于 DOM 中的行
推荐阅读
- wordpress - 在 WordPress Astra 主题中使用 Polylang 的多语言页脚不起作用
- javascript - 如何使用javascript获取每行中多个输入字段的百分比
- polygon - 多边形表面重建
- css - WP Rocket - 优化 CSS 交付和 Divi 博客模块问题
- scala - Spark 2.4 - 数据帧写入 s3 存储桶
- sql - SQL - 仅检索一条相关记录的记录
- c++ - 指针指向结构中的另一个指针
- sql - Postgres 交叉表查询 动态数据透视
- php - 在同一台托管主机上包含来自不同网站的 PHP 文件?
- go - 我应该在 hystrix.Do 的 hystrix-go 包的运行参数中使用哪个 ctx?来自上层的 ctx,还是 context.Background()?