可编辑表格html+css+js

我是利用的json导入的数据,并可对相应的数据在表格中增删改

JSON

{
  "students": [
    {
      "id": 202301,
      "name": "张三",
      "english": 88,
      "math": 99,
      "chinese": 100
    },
    {
      "id": 202302,
      "name": "李四",
      "english": 73,
      "math": 69,
      "chinese": 90
    }
  ]
}

HTML(采取表头固定的方式)

<div class="warpper" style="text-align: center">
      <label for="studentName">姓名:</label>
      <input type="text" id="studentName" name="studentName" required />
      <label for="english">英语:</label>
      <input type="text" id="english" name="english" required />
      <label for="math">数学:</label>
      <input type="text" id="math" name="math" required />
      <label for="chinese">语文:</label>
      <input type="text" id="chinese" name="chinese" required />
      <button id="increase">新增</button>
      <table class="myTable" id="myTable">
        <thead>
          <th>学号</th>
          <th>姓名</th>
          <th>英语</th>
          <th>数学</th>
          <th>语文</th>
          <th>总分</th>
          <th>删除</th>
        </thead>
      </table>
    </div>

JS

const idReg = "^\\d{3}$";
    const nameReg = "^[\\u4e00-\\u9fa5]{2,4}$";
    const gradReg = "^([0-9]{1,2}|100)$";
    const myTable = document.getElementById("myTable");

    const instance = axios.create({
      baseURL: "http://localhost:3000/students",
      timeout: 10000,
    });

    const thead = myTable.querySelector("thead");
    console.log(thead);

    // 查询渲染信息
    function getData() {
      instance
        .get("")
        .then((res) => {
          const studentsData = res.data;
          console.log(res.data);
          let studentsList = "";
          for (let student of studentsData) {
            const rowData =
              `<tr>` +
              `<td contenteditable='true' data-reg='${idReg}'>${student.id}</td>` +
              `<td contenteditable='true' data-reg='${nameReg}'>${student.name}</td>` +
              `<td contenteditable='true' data-reg='${gradReg}'>${student.english}</td>` +
              `<td contenteditable='true' data-reg='${gradReg}'>${student.math}</td>` +
              `<td contenteditable='true' data-reg='${gradReg}'>${student.chinese}</td>` +
              `<td id="total">${
                student.chinese + student.math + student.english
              }</td>` +
              `<td><button  class='deleteBtn' id="${student.id}">删除</button></td>` +
              `</tr>`;
            studentsList += rowData;
          }
          myTable.innerHTML += studentsList;
          Delete();
        })
        .catch((error) => {
          console.log(error);
        });
    }
    getData();

    // 修改数据

    myTable.addEventListener(
      "click",
      function (e) {
        const td = e.target;
        const total = td.parentNode.childNodes[5];
        const reg = new RegExp(td.dataset.reg);
        if (td.tagName === "TD") {
          const text = td.innerHTML;
          td.innerHTML = "";
          const input = document.createElement("input");
          input.type = "text";
          input.style.border = "none";
          input.style.outline = "none";
          input.style.textAlign = "center";
          input.style.width = "110px";
          input.style.height = "48px";
          input.style.fontSize = "16px";
          input.value = text;
          td.appendChild(input);
          input.focus();
          input.addEventListener(
            "blur",
            (e) => {
              const input = e.target;
              const newValue = input.value;
              if (reg.test(newValue)) {
                td.innerHTML = newValue;
                total.innerHTML =
                  parseInt(total.innerHTML) +
                  parseInt(newValue) -
                  parseInt(text);
                instance.post;
              } else {
                alert("不符合");
                td.innerHTML = text;
              }
            },
            false
          );
        }
      },
      false
    );

    // 删除数据

    function Delete() {
      const delButtons = document.querySelectorAll(".deleteBtn");
      delButtons.forEach((one) => {
        one.addEventListener("click", function (event) {
          const id = event.target.getAttribute("id");
          instance
            .delete(`/${id}`)
            .then((res) => {
              console.log(res.data);
              getData();
            })
            .catch((err) => {
              console.error(err);
            });
        });
      });
    }

    //增加数据
    const increase = document.getElementById("increase");
    increase.addEventListener("click", (e) => {
      const studentName = document.getElementById("studentName").value;
      const english = document.getElementById("english").value;
      english > 0 && english <= 100 ? english : (english = 0);
      const math = document.getElementById("math").value;
      math > 0 && math <= 100 ? math : (math = 0);
      const chinese = document.getElementById("chinese").value;
      chinese > 0 && chinese <= 100 ? chinese : (chinese = 0);
      instance
        .post("/", {
          name: String(studentName),
          english: Number(english),
          math: Number(math),
          chinese: Number(chinese),
        })
        .then((res) => {
          console.log(res.data);
          getData();
        })
        .catch((err) => {
          console.error(err);
        });
    });

整体如下

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="axios.js"></script>
    <style>
      .warpper {
        position: relative;
        margin-top: 10%;
      }

      .myTable {
        table-layout: fixed;
        width: 0;
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        border: 1px solid #000;
        border-collapse: collapse;
      }

      th {
        background-color: #ffd220;
      }

      input {
        background-color: greenyellow;
      }

      th,
      td {
        width: 120px;
        height: 50px;
        text-align: center;
        border: 1px solid #000;
        font-size: 16px;
      }
    </style>
  </head>

  <body>
    <div class="warpper" style="text-align: center">
      <label for="studentName">姓名:</label>
      <input type="text" id="studentName" name="studentName" required />
      <label for="english">英语:</label>
      <input type="text" id="english" name="english" required />
      <label for="math">数学:</label>
      <input type="text" id="math" name="math" required />
      <label for="chinese">语文:</label>
      <input type="text" id="chinese" name="chinese" required />
      <button id="increase">新增</button>
      <table class="myTable" id="myTable">
        <thead>
          <th>学号</th>
          <th>姓名</th>
          <th>英语</th>
          <th>数学</th>
          <th>语文</th>
          <th>总分</th>
          <th>删除</th>
        </thead>
      </table>
    </div>
  </body>
  <script>
    // 验证规则
    const idReg = "^\\d{3}$";
    const nameReg = "^[\\u4e00-\\u9fa5]{2,4}$";
    const gradReg = "^([0-9]{1,2}|100)$";
    const myTable = document.getElementById("myTable");

    const instance = axios.create({
      baseURL: "http://localhost:3000/students",
      timeout: 10000,
    });

    const thead = myTable.querySelector("thead");
    console.log(thead);

    // 查询渲染信息
    function getData() {
      instance
        .get("")
        .then((res) => {
          const studentsData = res.data;
          console.log(res.data);
          let studentsList = "";
          for (let student of studentsData) {
            const rowData =
              `<tr>` +
              `<td contenteditable='true' data-reg='${idReg}'>${student.id}</td>` +
              `<td contenteditable='true' data-reg='${nameReg}'>${student.name}</td>` +
              `<td contenteditable='true' data-reg='${gradReg}'>${student.english}</td>` +
              `<td contenteditable='true' data-reg='${gradReg}'>${student.math}</td>` +
              `<td contenteditable='true' data-reg='${gradReg}'>${student.chinese}</td>` +
              `<td id="total">${
                student.chinese + student.math + student.english
              }</td>` +
              `<td><button  class='deleteBtn' id="${student.id}">删除</button></td>` +
              `</tr>`;
            studentsList += rowData;
          }
          myTable.innerHTML += studentsList;
          Delete();
        })
        .catch((error) => {
          console.log(error);
        });
    }
    getData();

    // 修改数据

    myTable.addEventListener(
      "click",
      function (e) {
        const td = e.target;
        const total = td.parentNode.childNodes[5];
        const reg = new RegExp(td.dataset.reg);
        if (td.tagName === "TD") {
          const text = td.innerHTML;
          td.innerHTML = "";
          const input = document.createElement("input");
          input.type = "text";
          input.style.border = "none";
          input.style.outline = "none";
          input.style.textAlign = "center";
          input.style.width = "110px";
          input.style.height = "48px";
          input.style.fontSize = "16px";
          input.value = text;
          td.appendChild(input);
          input.focus();
          input.addEventListener(
            "blur",
            (e) => {
              const input = e.target;
              const newValue = input.value;
              if (reg.test(newValue)) {
                td.innerHTML = newValue;
                total.innerHTML =
                  parseInt(total.innerHTML) +
                  parseInt(newValue) -
                  parseInt(text);
                instance.post;
              } else {
                alert("不符合");
                td.innerHTML = text;
              }
            },
            false
          );
        }
      },
      false
    );

    // 删除数据

    function Delete() {
      const delButtons = document.querySelectorAll(".deleteBtn");
      delButtons.forEach((one) => {
        one.addEventListener("click", function (event) {
          const id = event.target.getAttribute("id");
          instance
            .delete(`/${id}`)
            .then((res) => {
              console.log(res.data);
              getData();
            })
            .catch((err) => {
              console.error(err);
            });
        });
      });
    }

    //增加数据
    const increase = document.getElementById("increase");
    increase.addEventListener("click", (e) => {
      const studentName = document.getElementById("studentName").value;
      const english = document.getElementById("english").value;
      english > 0 && english <= 100 ? english : (english = 0);
      const math = document.getElementById("math").value;
      math > 0 && math <= 100 ? math : (math = 0);
      const chinese = document.getElementById("chinese").value;
      chinese > 0 && chinese <= 100 ? chinese : (chinese = 0);
      instance
        .post("/", {
          name: String(studentName),
          english: Number(english),
          math: Number(math),
          chinese: Number(chinese),
        })
        .then((res) => {
          console.log(res.data);
          getData();
        })
        .catch((err) => {
          console.error(err);
        });
    });
  </script>
</html>

实现效果

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值