Javascript - 使用 document.execcommand 添加行现有表,但我犯了一些错误,但我不知道它在哪里

标签 javascript

我正在开发编辑器,但我无法理解这个范围概念。 我想使用 exec 命令添加表的第一行。我在下面插入了一张图片。

My expected output image

 function addRow() {
    let range = document.createRange();
    let sel = window.getSelection();
    let el = document.querySelector("tbody");
    range.setStartBefore(el.firstChild);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
    let b = `<tr>
        <td>Mary</td>
        <td>Moe</td>
        <td>mary@example.com</td>
      </tr>`;
    document.execCommand("insertHTML", false, b);
  }
<table class="table table-bordered" contenteditable="true">
    <thead>
      <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Email</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>John</td>
        <td>Doe</td>
        <td>john@example.com</td>
      </tr>
      <tr>
        <td>Mary</td>
        <td>Moe</td>
        <td>mary@example.com</td>
      </tr>
      <tr>
        <td>July</td>
        <td>Dooley</td>
        <td>july@example.com</td>
      </tr>
    </tbody>
  </table>
  <button onclick="addRow()">Add Row</button>
  
 

最佳答案

您可以使用insertAdjacentHTML将 HTML 文本插入到任意位置。

function addRow() {
    let el = document.querySelector("tbody");    
    let newRow = getRow(["Mary","Moe","mary@example.com"]);
    el.insertAdjacentHTML("afterbegin", newRow);
 }
 
 function getRow(dataArray) {
    let rowData = dataArray.map(data => `<td>${data}</td>`).join("");
    return `<tr>${rowData}</tr>`;
    
 }
<table class="table table-bordered" contenteditable="true">
    <thead>
      <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Email</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>John</td>
        <td>Doe</td>
        <td>john@example.com</td>
      </tr>
      <tr>
        <td>Mary</td>
        <td>Moe</td>
        <td>mary@example.com</td>
      </tr>
      <tr>
        <td>July</td>
        <td>Dooley</td>
        <td>july@example.com</td>
      </tr>
    </tbody>
  </table>
  <button onclick="addRow()">Add Row</button>

关于Javascript - 使用 document.execcommand 添加行现有表,但我犯了一些错误,但我不知道它在哪里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60090028/

相关文章:

javascript - 使用数据: URI?时有没有办法指定建议的文件名

javascript - 如果超过值,则在文本框上显示弹出框

javascript - 如何快速将多行附加到 div(一次一行)并使用 Vue 滚动到底部?

javascript - Rails with Bootstrap - 日期选择器

javascript - 更改日期,使所有时间偏移 4 小时

javascript - 如何使用 JS/jQuery 正确提交动态创建的表单?

php - 使用 JSON,将变量从 php 传递到 javascript

javascript - 单击后重新启用按钮@click.once

javascript - React - 使用 bootstrap 创建 Accordion 不会在点击时展开/关闭

javascript - 将更新的子状态转换为父状态