【问题标题】:How to append row to html table using javascript?如何使用javascript将行附加到html表?
【发布时间】:2020-11-05 06:40:21
【问题描述】:

我正在创建一个 google chrome 扩展程序并尝试在 html 表中记录数据。我目前无法尝试将行附加到我的 html 表中。我正在尝试将其移至每次用户访问新网址时另一行添加到表中的位置。

Picture of chrome extension

以下是我当前的代码:

Manifest.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);
    
    
}

【问题讨论】:

    标签: javascript url google-chrome-extension html-table append


    【解决方案1】:

    相信你在使用insertRow的时候,table的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;
                }
    
    

    【讨论】:

      猜你喜欢
      • 2016-02-13
      • 1970-01-01
      • 1970-01-01
      • 2016-12-09
      • 2020-09-11
      • 1970-01-01
      • 2013-06-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多