Jquery:在包含特定列值的行之后插入新行

时间:2018-03-06 03:17:40

标签: jquery find append insertafter

如何使用Jquery在具有特定列值的行之后追加新行?

例如,我希望在' Selina'之后添加一列新的专栏[NAME:CINDY AGE:21]。因为我希望添加一个新行,按照' AGE'并且[NAME:Tori AGE:26]将在' Kelly'之后追加。

<table>
  <tr>
    <th>NAME</th>
    <th>AGE</th>
  </tr>
  <tbody>
    <tr>
      <td>Alice</td>
      <td>18</td>
    </tr>
    <tr>
      <td>Selina</td>
      <td>20</td>
    </tr>
    <tr>    
      <td>Kelly</td>
      <td>25</td>
    </tr>
  </tbody>
</table>
<input type="text" name="name" id="name" placeholder="NAME">
<input type="text" name="age" id="age" placeholder="AGE">
<button type="button" id="add_btn">ADD</button>

谢谢。欢呼:)

2 个答案:

答案 0 :(得分:2)

这应该有效:

jQuery('#add_btn').on('click',function(){
  var age = jQuery('#age').val();
  var name = jQuery('#name').val();
    var target = jQuery('tbody > tr > td:last-child').filter(function(){
    return jQuery(this).text() >= age;
  }).first().parent();
  if(target.length > 0)
    target.before('<tr><td>'+name+'</td><td>'+age+'</td></tr>');
  else
    jQuery('tbody > tr:last').after('<tr><td>'+name+'</td><td>'+age+'</td></tr>');
});

jsFiddle

答案 1 :(得分:0)

&#13;
&#13;
function myFunction() {
  document.getElementById('test').innerHTML = document.getElementById('test').innerHTML + "<tr><td>" + document.getElementById('name').value + "</td><td>" + document.getElementById('age').value + "</td></tr>";
}
&#13;
<!DOCTYPE html>
<html>

<head>
  <title>TODO supply a title</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body>
  <table id="test">

    <tr>
      <th>NAME</th>
      <th>AGE</th>
    </tr>
    <tbody>
      <tr>
        <td>Alice</td>
        <td>18</td>
      </tr>
      <tr>
        <td>Selina</td>
        <td>20</td>
      </tr>
      <tr>
        <td>Kelly</td>
        <td>25</td>
      </tr>
    </tbody>
  </table>
  <input type="text" name="name" id="name" placeholder="NAME">
  <input type="text" name="age" id="age" placeholder="AGE">
  <button type="button" onclick="myFunction()">ADD</button>

</body>

</html>
&#13;
&#13;
&#13;