我有一个包含一些可编辑单元格的表格/。我可以毫无问题地获取更新的值并保存更改。我网站的一部分是跟踪更改历史记录,因此我需要知道是否有 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/