jQuery实现列表的增加和删除功能

jQuery实现列表的增加和删除功能

具体代码如下所示:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>jQuery</title>
  <style>
  </style>
</head>
<body>
  <div>
    <table style="margin: 10px auto;" id="tableList">
      <thead>
        <tr>
          <th>name</th>
          <th>price</th>
          <th>delete</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>a</td>
          <td>123</td>
          <td><a href="#" rel="external nofollow" rel="external nofollow" >delete</a></td>
        </tr>
        <tr>
          <td>c</td>
          <td>3453</td>
          <td><a href="#" rel="external nofollow" rel="external nofollow" >delete</a></td>
        </tr>
      </tbody>
    </table>
  </div>
  <form>
    <table style="margin:0 auto;">
      <tr>
        <td>name</td>
        <td><input type="text" name="name"></td>
      </tr>
      <tr>
        <td>price</td>
        <td><input type="text" name="price"></td>
      </tr>
      <tr>
        <td colspan="2">
          <input type="submit" value="submit" id="add">
        </td>
      </tr>
    </table>
  </form>
<script src="../js/vendor/jquery-3.2.1.min.js"></script>
<script>
  var $tableList=$("#tableList");
  //tianjia
  $("#add").click(function(){
    var tdName= $("input[name=name]").val();
    var tdPrice = $("input[name=price]").val();
    $("<tr></tr>").append("<td>"+tdName+"</td>")
      .append("<td>"+tdPrice+"</td>")
      .append("<td><a href='#?'>delete</a></td>")
      .appendTo($("#tableList>tbody"))
      .find("a").click(function(){
       $(this).parent().parent().remove();
      });
      $("input[name=name]").val("");
      $("input[name=price]").val("");
    return false;
  })
  //delete
  $("#tableList>tbody a").click(function(){
    $(this).parent().parent().remove();
  })
</script>
</body>
</html>

总结

相关推荐