首页 > 解决方案 > 在另一行之前和之后追加行

问题描述

<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 行上方创建新行。需要示例函数!

标签: javascriptjqueryhtml

解决方案


使用JQUERY

参考:jQuery.closestjQuery beforejQuery afterjQuery 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 cloneNodeJS 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>


推荐阅读