我是使用脚本语言的新手。我试图将表的内容存储到一个csv文件中。网页将显示一个包含两行的表,并且可以动态添加或删除一行。我正在尝试存储所有表内容保存到csv文件中。但是,它只存储给定的内容,即此处的head标签(th),不存储输入内容(td-单元格数据)。有人可以帮我解决这个错误。
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".add-row").click(function(){
var markup = "<tr><td><input type='checkbox' name='record'></td><td><input type='text'></td><td><input type='text'></td><td><input type='text'></td><td><input type='text'></td><td><input type='text'></td><td><input type='text'></td></tr>";
$("table tbody").append(markup);
});
$(".delete-row").click(function(){
$("table tbody").find('input[name="record"]').each(function(){
if($(this).is(":checked")){
$(this).parents("tr").remove();
}
});
});
});
<script>
function download_csv(csv, filename) {
var csvFile;
var downloadLink;
csvFile = new Blob([csv], {type: "text/csv"});
downloadLink = document.createElement("a");
downloadLink.download = filename;
downloadLink.href = window.URL.createObjectURL(csvFile);
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
function export_table_to_csv(html, filename) {
var csv = [];
var rows = document.querySelectorAll("table tr");
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll(".td,td,th");
for (var j = 0; j < cols.length; j++)
row.push(cols[j].innerText);
csv.push(row.join(","));
}
download_csv(csv.join("\n"), filename);
}
document.querySelector(".save_data").addEventListener("click", function () {
var html = document.querySelector("table").outerHTML;
export_table_to_csv(html, "table.csv");
});
</script>
<!DOCTYPE html>
<html>
<body>
<button type="button" class="delete-row" style="float: right;">Delete Row</button>
<input type="button" class="add-row" value="Add Row" style="float: right;">
<table border=3>
<tr>
<th>Select</th>
<th>S.No</th>
<th>Sem</th>
<th>Course Code</th>
<th>Course Name</th>
<th>Category (PC/PE/OE/BS/FC/ES/HS/ONE CREDIT)</th>
<th>Credit</th>
</tr>
<tr>
<td><input type="checkbox" name="record"></td>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
<tr>
<td><input type="checkbox" name="record"></td>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
</table>
<button type="button" name="save_data" class="save_data">Enroll</button>
</body>
</html>