javascript - 在另一行之前和之后追加行
问题描述
<table id="thisTable">
<tr>
<th>ID</th>
<th>Name</th>
</tr>
<tr>
<td><input></td>
<td><input></td>
</tr>
<tr>
<td><input></td>
<td><input></td>
</tr>
<tr>
<td><input></td>
<td><input></td>
</tr>
<tr>
<td><input></td>
<td><input></td>
</tr>
</table>
<button onclick="prePend()">Insert Above</button>
<button onclick="appPend()">Inser Below</button>
单击此表单中的某些文本输入,然后单击按钮Insert Above
/ Insert Below
,将在焦点输入引用的位置创建一个新行。
示例:点击第 2 行的输入,然后点击 Insert Above 按钮 -- 将在第 2 行上方创建新行。需要示例函数!
解决方案
使用JQUERY:
参考:jQuery.closest、jQuery before、jQuery after、jQuery html
var selectedinput;
document.addEventListener("focus",function(event){
if(event.target.tagName.toLowerCase()==="input"){
selectedinput = event.target;
}
},true);
function insert(pos)
{
if(!selectedinput) return;
var tr = $(selectedinput).closest("tr");
pos=='above' ? tr.before(tr.html()) : tr.after(tr.html());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="thisTable">
<tr>
<th>ID</th>
<th>Name</th>
</tr>
<tr>
<td><input></td>
<td><input></td>
</tr>
<tr>
<td><input></td>
<td><input></td>
</tr>
<tr>
<td><input></td>
<td><input></td>
</tr>
<tr>
<td><input></td>
<td><input></td>
</tr>
</table>
<button onclick="insert('above')">Insert Above</button>
<button onclick="insert('below')">Inser Below</button>
使用JAVASCRIPT:
参考:JS cloneNode,JS insertAdjacentElement
var selectedinput;
document.addEventListener("focus",function(event){
if(event.target.tagName.toLowerCase()==="input"){
selectedinput = event.target;
}
},true);
function insert(pos)
{
if(!selectedinput) return;
var tr = selectedinput.parentElement.parentElement;
var elem = tr.cloneNode(true);
//Clone node not supported in Opera - following can be used
//var elem = document.createElement("tr")†;
//elem.innerHTML=tr.innerHTML
tr.insertAdjacentElement((pos=='above' ? 'beforeBegin':'afterEnd'),elem );
}
<table id="thisTable">
<tr>
<th>ID</th>
<th>Name</th>
</tr>
<tr>
<td><input></td>
<td><input></td>
</tr>
<tr>
<td><input></td>
<td><input></td>
</tr>
<tr>
<td><input></td>
<td><input></td>
</tr>
<tr>
<td><input></td>
<td><input></td>
</tr>
</table>
<button onclick="insert('above')">Insert Above</button>
<button onclick="insert('below')">Inser Below</button>
推荐阅读
- php - 带有新身份验证方法的 Symfony 简单登录表单不起作用
- r - 如何使用 dplyr 获取交叉表(group_by)以包含 0?
- visual-studio-code - 在 VScode 中使用多个光标进行搜索
- python - Python:Kivy 模块不显示小部件
- ios - 移动数据开启时 iOS 无法连接到本地套接字
- image-processing - 使用 ImageMagick 跟踪鼠标路径?
- swift - 如何使用单例对模型控制器进行单元测试
- flutter - 将淡入淡出应用于图像或组件(模糊、渐变)
- coq - 如何一次应用于多个假设?
- excel - VBA/宏问题创建正确高度/宽度的表格并在没有电子表格最后一行的情况下创建该表格