如何编辑选定的 html 列?

问题描述

我有一个包含名称和分数的表格。用户可以选择一个分数列,然后列标题将出现在输入字段中。我希望用户可以编辑它。

这是我写的代码

var rIndex,table = document.getElementById("table");
var key = ["scores 1","scores 2","scores 3"];

showHeader();

function showHeader(){
    var header = ""; 

    header += '<th class="th-chart">Name</th>';

    for(var i = 0; i < key.length; i++) {
       header += '<th class="th-chart" onclick="selectedCell(' + i + ')">' + key[i] + '</th>';
    }

    document.getElementById("header").innerHTML = header;
}

function selectedCell(index){  
   cIndex = index;
   document.getElementById("scores").value = key[cIndex];
}

function editColumn(){
}
<table class="table table-borderless table-chart" id="table" width="100%" cellspacing="0">
   <thead>
      <tr class="tr-chart" id="header">
                                                    
      </tr>
   </thead>
   <tbody id="table-body">
      <tr class="tr-chart">
          <td>Student 1</td>
          <td>100</td>
          <td>100</td>
          <td>100</td>
      </tr>     
      <tr class="tr-chart">
          <td>Student 2</td>
          <td>200</td>
          <td>200</td>
          <td>200</td>
      </tr>
   </tbody>
</table><br>

<label class="form-control-label" for="scores">scores:</label>
<input class="form-control" name="scores" id="scores" type="text">
<button class="btn btn-primary" onclick="editColumn();">Edit</button>

解决方法

你可以这样做:

var rIndex,table = document.getElementById("table");
var key = ["Scores 1","Scores 2","Scores 3"];

const modul = document.getElementById("modul");

showHeader();

function showHeader() {
  var header = "";

  header += '<th class="th-chart">Name</th>';

  for (var i = 0; i < key.length; i++) {
    header +=
      '<th class="th-chart" onclick="selectedCell(' +
      i +
      ')">' +
      key[i] +
      "</th>";
  }

  document.getElementById("header").innerHTML = header;
}

let cIndex;

function selectedCell(index) {
  cIndex = index;
  modul.value = key[cIndex];
}

function editColumn() {
  if (cIndex && modul.value !== "") {
    key[cIndex] = modul.value;
    showHeader();
    modul.value = "";
  }
}
<table class="table table-borderless table-chart" id="table" width="100%" cellspacing="0">
  <thead>
    <tr class="tr-chart" id="header"></tr>
  </thead>
  <tbody id="table-body">
    <tr class="tr-chart">
      <td>Student 1</td>
      <td>100</td>
      <td>100</td>
      <td>100</td>
    </tr>
    <tr class="tr-chart">
      <td>Student 2</td>
      <td>200</td>
      <td>200</td>
      <td>200</td>
    </tr>
  </tbody>
</table>
<br />

<label class="form-control-label" for="Modul">Modul:</label>
<input class="form-control" name="modul" id="modul" type="text" />
<button class="btn btn-primary" onclick="editColumn();">Edit</button>

,

尝试使用一些 jQuery 可编辑表,它将为您提供具有许多功能的完整 CRUD 体验 请检查此链接,它将对您有很大帮助 http://www.trirand.com/blog/?page_id=5