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

标签 javascript jquery html

我有一个包含一些可编辑单元格的表格/。我可以毫无问题地获取更新的值并保存更改。我网站的一部分是跟踪更改历史记录,因此我需要知道是否有 Javascript 或 JQuery 可以从页面最初加载时获取单元格/的原始值。 (与输入的 .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>

工作示例 here .

更新

如果您想使用 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>

示例 here .

关于javascript - 获取可编辑 <td> 的原始文本/值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35962548/

相关文章:

javascript - Phonegap 入门

javascript - 该网站在 ie 中使用脚本窗口错误

css - 连续 3 个 div - 无法让最右边的 div 对齐

html - 如何让背景图片覆盖整个页面

html - 有没有办法使用 Selenium/WebDriver 提取 html 评论?

javascript - 没有jquery突出导航

javascript - AngularJS 指令中的设置模型为空

javascript - 强制 CSS 转换在 JavaScript 函数中多次更新

jQuery 动画性能

javascript - 更新 Uniform.js 输入不起作用