javascript - 如何使用javascript将行附加到html表?
问题描述
我正在创建一个 google chrome 扩展程序并尝试在 html 表中记录数据。我目前无法尝试将行附加到我的 html 表中。我试图让它到达每次用户访问新 url 时都会在表中添加另一行的位置。
以下是我当前的代码:
清单.json
{
//Required naming
"name" : "Activity logger",
"version": "1.0",
"manifest_version": 2,
"description": "This support includes the development of a Chrome Browser Activity Logger.",
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js", "popup.js"]
}
],
"browser_action": {
"default_icon": "act.png",
"default_title": "Activity",
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"]
},
"permissions": ["tabs", "storage"]
}
popup.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>
Activity Logger
</title>
<style>
*{
color:#2b2b2b;
font-family: "Roboto Condensed";
}
table{ width:40%;}
th{ text-align:left; color:#4679bd}
tbody > tr:nth-of-type(even) { background-color:#daeaff;)
button( cursor:pointer; margin-top:1rem;)
</style>
</head>
<body>
<script src="popup.js" charset="utf-8"></script>
<h2>Activity Logger</h2>
<table id = "tableID" border="1">
<!--Example table header row with the user, url visited, and time they visited the url etc-->
<tr>
<!--categories-->
<th>Browser</th>
<th>Timestamp</th>
<th>URL</th>
<th>Protocol</th>
<th>Downloaded File Names</th>
<th>Description</th>
</tr>
<tr id='myRow'>
<!--1st row-->
<td>Google</td>
<td>000000</td>
<td>https://stackoverflow.com/questions/ask</td>
<td>example</td>
<td>example</td>
<td>example</td>
</tr>
<!--Goal is to append to this table-->
</table>
<!--when clicked it, ID uses function, exportTableToCSV to download file-->
<a id="click-this">
<u> Save as CSV </u>
</a>
</body>
</html>
popup.js
//loads element url on page--draft
document.addEventListener('DOMContentLoaded', function () {
const bg = chrome.extension.getBackgroundPage()
Object.keys(bg.bears).forEach(function (url) {
const div = document.createElement('div')
div.textContent = `${url}`
document.body.appendChild(div)
})
}, false)
// creates ID to export table to csv--works
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("click-this").addEventListener("click", exportTableToCSV);
});
//--underwork--
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("tableID").addEventListener("click", addRow);
});
//function to append row to HTML table --underwork--
function addRow() {
//perhaps need an for loop for every page visited
//get html table
// Append product to the table
var table = document.getElementByID("tableID");
// add new empty row to the table
// 1 = in the top (say you wanna have the most recent link visited at the top row after the header)
// table.rows.length = the end
// table.rows.length/2+1 = the center (probably not useful for you)
var newRow = table.insertRow(1);
// add cells to the row
var nameCell = newRow.insertCell(0);
var urlCell = newRow.insertCell(1);
var timeCell = newRow.insertCell(2);
// add the data to the cells
nameCell.innerHTML = USERNAME;
urlCell.innerHTML = URL_VISITED;
timeCell .innerHTML = TIMESTAM;
}
//perhaps add row using JQuery--underwork
/*function addRowUsingJquery() {
// Get a reference to your table
let table = document.querySelector('#tableID');
// Build the row
let template = `
<tr>
<td>${USERNAME}</td>
<td>${URL_VISITED}</td>
<td>${TIMESTAMP}</td>
</tr>`;
// Add the row to the end of the table
table.innerHTML += template;
}
*/
//function to for onClick function--works
function downloadCSV(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";
downloadLink.setAttribute("download", "data.csv");
document.body.appendChild(downloadLink);
downloadLink.click();
}
//function to export HTML table to csv file--works
function exportTableToCSV(filename) {
var csv = [];
var rows = document.querySelectorAll("table tr");
for(var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll("td, th");
for(var j=0; j < cols.length; j++)
row.push(cols[j].innerText);
csv.push(row.join(","));
}
//download csv file
downloadCSV(csv.join("\n"), filename);
}
解决方案
我相信当你使用insertRow时,表格的html需要有一个tbody
http://jsfiddle.net/4sR2G/
https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/insertRow
所以 html 表的格式应该是:
<table id="tableID">
<thead>
<tr>
<th>Browser</th>
<th>Timestamp</th>
<th>URL</th>
<th>Protocol</th>
<th>Downloaded File Names</th>
<th>Description</th>
</tr>
</thead>
<tbody id="tbodyID">
<tr>
<td>Google</td>
<td>000000</td>
<td>https://stackoverflow.com/questions/ask</td>
<td>example</td>
<td>example</td>
<td>example</td>
</tr>
</tbody>
</table>
然后,您可以更改 JS 以反映这些更改:
//function to append row to HTML table --underwork--
function addRow() {
//perhaps need an for loop for every page visited
//get html table
// Append product to the table
var table = document.getElementById("tbodyID");
// add new empty row to the table
// 1 = in the top (say you wanna have the most recent link visited at the top row after the header)
// table.rows.length = the end
// table.rows.length/2+1 = the center (probably not useful for you)
// insertRow(0) as top of body (excludes head)
var newRow = table.insertRow(0);
// add cells to the row
var nameCell = newRow.insertCell(0);
var urlCell = newRow.insertCell(1);
var timeCell = newRow.insertCell(2);
// add the data to the cells
nameCell.innerHTML = USERNAME;
urlCell.innerHTML = URL_VISITED;
timeCell.innerHTML = TIMESTAM;
}
推荐阅读
- linux - 如何快速找到链接时需要存在另一个对象图块的对象文件?
- vim - Vim 无法识别来自 vim-latex 的某些命令
- python - 从 Python 2 转换为 3。使用 cmp 进行排序
- c# - 关于在 C# 中执行 while 循环的问题
- c++ - 如何从棋盘上的框号中查找行和列?
- c# - 必须通过 Modbus TCP 通过 Modbus RTU 为轮询 RS485 编写客户端吗?
- asynchronous - 使用带有颤振地图的期货
- c - 如何检查本身是无符号变量的负数(通过用户输入)?
- php - 如何在 PHPUnit 测试中“模拟”Sentry 客户端
- android - 使用导航组件在父片段范围内共享 ViewModel