function createTable(){
var _table = document.getElementById("test");
var newRow = _table.insertRow(1);
var cell0 = newRow.insertCell(0);
var cell1 = newRow.insertCell(1);
cell0.innerHTML = "x";
cell1.innerHTML = 60;
}
function saveTable(){
document.execCommand("saveas",,"/tmp/test.html");
}
<p>to create my table</p>
<input type="button" value="to create new table" onclick="createTable()" />
<input type="button" value="to save table as /tmp/test.html" oncilck="saveTable()" />
<table id="test" bodrder=1px>
<tr>
<td>f1</td>
<td>f2</td>
</tr>
</table>
当表格是由createTable函数创建的时候,我想得到一个文件/tmp/test.html,其内容如下:
<table id="test">
<tr>
<td>f1</td>
<td>f2</td>
</tr>
<tr>
<td>x</td>
<td>60</td>
</tr>
</table>
如何完成我的saveTable功能来完成这项工作?
答案 0 :(得分:1)
你可以使用blob,如下所述:
在这里:
How to export source content within div to text/html file
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p>to create my table</p>
<form>
<input type="button" value="to create new table" onclick="createTable()"> <input type="button" value=
"to save table as /tmp/test.html" onclick="saveTable()">
</form>
<table id="test" bodrder="1px">
<tr>
<td>f1</td>
<td>f2</td>
</tr>
</table>
<script>
function createTable() {
var _table = document.getElementById("test");
var newRow = _table.insertRow(1);
var cell0 = newRow.insertCell(0);
var cell1 = newRow.insertCell(1);
cell0.innerHTML = "x";
cell1.innerHTML = 60;
}
function saveTable() {
var textToSave = document.getElementById("test").outerHTML;
var textToSaveAsBlob = new Blob([textToSave], {
type : "text/html"
});
var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
var fileNameToSaveAs = "/tmp/test.html";
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
downloadLink.href = textToSaveAsURL;
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
function destroyClickedElement(event) {
document.body.removeChild(event.target);
}
</script>
</body>
</html>