获取可编辑 <td> 的原始文本/值

Get original text/value of editable <td>

本文关键字:原始 文本 td 编辑 获取      更新时间:2023-09-26

我有一个表格,里面有一些可编辑的单元格/。 我可以毫无问题地获取更新的值并保存更改。 我网站的一部分是跟踪更改历史记录,所以我需要知道 Javascript 或 JQuery 是否有任何内容来获取 cell/的原始值,从最初加载页面时开始。 (与输入的 .defaultValue 相当的东西会很好。

我一直在环顾四周,但没有找到任何可以真正做到这一点的东西。

谢谢乍得

您可以使用 data 属性。这里的基本示例:

<!doctype html>
<html>
<body>
  <div id="example" data-init="This is the initial content.">This is the initial content.</div>
  <button id="show" type="button">Click here to show the initial content</button>
<script>
  var exampleDIV = document.getElementById('example'),
      showBUTTON = document.getElementById('show');
  // change the content of the element
  exampleDIV.innerHTML = 'The content has been changed.';
  // get the initial content
  showBUTTON.addEventListener('click',function(){
    alert(exampleDIV.getAttribute('data-init'));
  });
</script>
</body>
</html>

这里的工作示例。

更新

如果你想用JavaScript插入数据属性,你可以使用这个:

<!doctype html>
<html>
<body>
<table id="sample">
  <tr>
    <td contentEditable="true">Initial Value 01</td>
    <td contentEditable="true">Initial Value 02</td>
    <td contentEditable="true">Initial Value 03</td>
  </tr>
  <tr>
    <td contentEditable="true">Initial Value 04</td>
    <td contentEditable="true">Initial Value 05</td>
    <td contentEditable="true">Initial Value 06</td>
  </tr>
  <tr>
    <td contentEditable="true">Initial Value 07</td>
    <td contentEditable="true">Initial Value 08</td>
    <td contentEditable="true">Initial Value 09</td>
  </tr>
  <tr>
    <td contentEditable="true">Initial Value 10</td>
    <td contentEditable="true">Initial Value 11</td>
    <td contentEditable="true">Initial Value 12</td>
  </tr>
</table>
<br>
Cell #<input id="cellno" name="cellno" type="number" min="1" max="12" value="1">
<button type="button" id="show">Show Initial Value</button>
<script>
  var sampleTABLE = document.getElementById('sample'),
      showBUTTON = document.getElementById('show'),
      cellnoINPUT = document.getElementById('cellno'),
      cellsTD = sampleTABLE.getElementsByTagName('td');
  // store all values in data attributes
  for(var i=0,l=cellsTD.length;i<l;i++){
    cellsTD[i].setAttribute('data-init',cellsTD[i].innerHTML);
  }
  // get the initial content
  showBUTTON.addEventListener('click',function(){
    alert(cellsTD[cellnoINPUT.value - 1].getAttribute('data-init'));
  });
</script>
</body>
</html>

这里的例子。