【问题标题】:How to dynamically insert rows into a table如何将行动态插入到表中
【发布时间】:2019-12-03 00:57:42
【问题描述】:

我有一张桌子,桌子是桌子,桌子是空的:

<table id ="floodTable" class ="gradient-style">
  <thead>
    <tr>
      <th>Event Name</th>
      <th>Date</th>
      <th style="text-align:right">Return Period</th>
    </tr>
  </thead>
  <tbody>
            ...//add stuff here...      
  </tbody>
</table>

我有一个引入 JSON 对象的 API。如果其中一个子对象满足某个条件,我想使用属性值来填充具有值的新行

“事件名称”(document.getElementById("floodTable").rows[0].cells[1]),
“日期”(document.getElementById("floodTable").rows[0].cells[2])和
“回归期”(document.getElementById("floodTable").rows[0].cells[3])

使用我的 API 可能会拉回符合我的条件的多个项目,我可能必须创建几行。我如何使用insertRow(0) 和/或insertCell(0) 来执行此操作?

【问题讨论】:

    标签: javascript dynamic html-table rows


    【解决方案1】:

    您可以使用HTMLTableElement.insertRow()HTMLTableRowElement.insertCell() 方法来实现:

    const form = document.querySelector('form');
    form.addEventListener('submit', event => {
      event.preventDefault();
      event.stopPropagation();
      
      const values = Object.values(form.elements).filter(el => el.id).map(el => el.value); 
      if (values.length === 3) {
        const table = document.querySelector('#floodTable tbody');
        const row = table.insertRow(0);
      
        values.forEach((val, ind) => {
          row.insertCell(ind).innerHTML = val;
        });
        form.reset();
        window.location.href = '#floodTable';
      }
    }, false);
    html {
      scroll-behavior: smooth;
    }
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" 
          rel="stylesheet"/>
    <div class="container">
      <table id="floodTable" class="table gradient-style">
        <thead>
          <tr>
            <th>Event Name</th>
            <th>Date</th>
            <th style="text-align:right">Return Period</th>
          </tr>
        </thead>
        <tbody>
    
        </tbody>
      </table>
      
      <div class="card">
        <form class="card-body">
          <div class="form-group">
            <label for="event">Event name:</label>
            <input type="text" class="form-control" id="event" required>
          </div>
          <div class="form-group">
            <label for="date">Date:</label>
            <input type="date" class="form-control" id="date" required>
          </div>
          <div class="form-group">
            <label for="period">Return period:</label>
            <input type="text" class="form-control" id="period" required>
          </div>
    
          <button type="submit" class="btn btn-primary">Add a row</button>
        </form>
      </div>
    </div>

    【讨论】:

    • 啊!不幸的是,不能使用 Bootstrap(过多地干扰现有的 css),但我能够得到它的一个变体来工作!
    猜你喜欢
    • 1970-01-01
    • 2014-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多