簡體   English   中英

在 HTML TABLE 中打印 JSON 使用本地存儲從另一個表保存,以便我在另一個頁面上打印我的表

[英]Printing JSON in HTML TABLE saved from another table using local storage so that i print my table on another page

在我的任務中,我必須使用從用戶輸入中獲取數據並將數據保存在本地存儲中。 我必須以水平表格式將本地存儲中的這些數據打印到其他頁面。為此,我編寫了用戶輸入代碼並將數據保存在本地存儲中

<style>
        data {
            color: #138bc2;
        }
    </style>
    <body>
   <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
   <div id="POItablediv">
   <p>
   <input type="button" id="bt" value="Submit Data" onclick="submit()" />
   </p>
   <input type="button" onclick="insRow()" id="addPOIbutton" value="Add values"/><br/><br/>
   <table id="POITable" border="1">
   <thead>
       <tr>
           <td>WEEK NO</td>
           <td>Daily exercise</td>
           <td>calorie</td>
           <td>food</td>
            <td>Revision no</td>
           <td>Delete?</td>

       </tr>
       </thead>
       <tbody>
       <tr>
           <td><input size=25 type="text" id="weekbox"/></td>
           <td><input size=25 type="text" id="latbox"/></td>
           <td><input size=25 type="text" id="lngbox"/></td>
           <td><input size=25 type="text" id="lnbox"/></td>
           <td><input size=25 type="text" id="lntbox"/></td>
           <td><input type="button" id="delPOIbutton" value="Delete" onclick="deleteRow(this)"/></td>

       </tr>
       <tbody>
   </table>
   </body>
   <script>
   function deleteRow(row)
    {
        var i=row.parentNode.parentNode.rowIndex;
        if(i>1){
        document.getElementById('POITable').deleteRow(i);
        }

    }


    function insRow()
    {

        var x=document.getElementById('POITable');
        var new_row = x.rows[1].cloneNode(true);
        var len = x.rows.length;
        new_row.cells[0].childNodes[0].value = "";

        var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
        inp1.id += len;
        inp1.value = '';
        var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
        inp2.id += len;
        inp2.value = '';
        x.appendChild( new_row );
        var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
        inp3.id += len;
        inp3.value = '';
        var inp4 = new_row.cells[4].getElementsByTagName('input')[0];
        inp4.id += len;
        inp4.value = '';
        x.appendChild( new_row );
    }
   function submit() 
   {
     var table = document.getElementById("POITable")
     var tableLen = table.rows.length           
     var data = {labels: [], alpha: [], beta: [],gamma:[]}

   for (var i = 1; i < tableLen; i++) 
  {
     data.labels.push(table.rows[i].cells[0].childNodes[0].value)
     data.alpha.push(table.rows[i].cells[1].childNodes[0].value)
     data.beta.push(table.rows[i].cells[2].childNodes[0].value)
     data.gamma.push(table.rows[i].cells[3].childNodes[0].value)
  }
 var alphadata = data
localStorage.setItem("quant", JSON.stringify(alphadata));

上面的代碼用於從用戶那里獲取輸入並保存在本地存儲中。我的目標是將數據從本地存儲打印到垂直 header 我的意思是表格的左側有 header () 標簽(通常)。

e<body>
<input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />
<p id="showData"></p>
 </body>

<script>
function CreateTableFromJSON() {
    var myBooks =JSON.parse(localStorage.getItem("quant"));

    var col = [];
    for (var i = 0; i < myBooks.length; i++) {
        for (var key in myBooks[i]) {
            if (col.indexOf(key) === -1) {
                col.push(key);
            }
        }
    }

    // CREATE DYNAMIC TABLE.
    var table = document.createElement("table");

    // CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.

    var tr = table.insertRow(-1);                   // TABLE ROW.

    for (var i = 0; i < col.length; i++) {
        var th = document.createElement("th");      // TABLE HEADER.
        th.innerHTML = col[i];
        tr.appendChild(th);
    }

    // ADD JSON DATA TO THE TABLE AS ROWS.
    for (var i = 0; i < myBooks.length; i++) {

        tr = table.insertRow(-1);

        for (var j = 0; j < col.length; j++) {
            var tabCell = tr.insertCell(-1);
            tabCell.innerHTML = myBooks[i][col[j]];
        }
    }

    // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
    var divContainer = document.getElementById("showData");
    divContainer.innerHTML = "";
    divContainer.appendChild(table);
    }
    </script>
    </html>

當我單擊第二頁中的按鈕時,表格未打印。 它給了我空白頁。 任何線索將不勝感激。

所以我沒有發現第一個將JSON數據插入本地存儲的文件有問題。 問題在於從第二個文件中獲取數據

<html>

<body>
    <input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />
    <p id="showData"></p>
</body>

<script>
    function CreateTableFromJSON() {
        var myBooks = JSON.parse(localStorage.getItem("quant"));
        console.log(myBooks);
        /* This logs the object to confirm whether it is there and to 
        confirm the values inside it You should make this a habit
        so that you can check for errors*/

        // var col = [];
        // for (var i = 0; i < myBooks.length; i++) {
        //     for (var key in myBooks[i]) {
        //         if (col.indexOf(key) == -1) {
        //             col.push(key);
        //         }
        //     }
        // }
        /* The code above is the one I have commented out and replaced with
        the one below to get both the keys and values in separate arrays */

        col_keys = Object.keys(myBooks);
        // Object.keys gets the keys of the object
        col_values = Object.values(myBooks);
        // Object.values gets the values in an object

        // CREATE DYNAMIC TABLE.
        var table = document.createElement("table");

        // CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.

        var tr = table.insertRow(-1);                   // TABLE ROW.

        /* --- REFERENCE 1 --- The length of col_keys and col_values is the same because they
        are key and value pairs */

        for (var i = 0; i < col_keys.length; i++) {
            var th = document.createElement("th");      // TABLE HEADER.
            th.innerHTML = col_keys[i];
            /* col_keys has the keys of the object which are added to
            the table header */
            tr.appendChild(th);
        }

        // ADD JSON DATA TO THE TABLE AS ROWS.

        for (var i = 0; i < col_values[0].length; i++) {

            /* The loop runs as many times as the number of items in each array
            EXPLANATION: col_values contains arrays.
            col_values[0].length returns the length of the first array, which is
            the array that contains the labels.
            And since all the arrays have the same length whether they have a value
            or not, the length of the first array is the same for all the others. 
            --- REFERENCE 2 --- In this case this outer loop runs 2 times*/

            tr = table.insertRow(-1);

            for (var j = 0; j < col_values.length; j++) {
                /* The inner loop runs as many times as the number of key-value pairs
                in the object.
                EXPLANATION: As " --- REFERENCE 1 --- " above says, this will run **4** times
                based on your current object which has:
                1.labels
                2.alpha
                3.beta
                4.gamma
                */
                var tabCell = tr.insertCell(-1);
                tabCell.innerHTML = col_values[j][i];
                /* Each time the loop runs, it inserts the "i" value of the array
                of each of the values of the object.
                Check " --- REFERENCE 2 --- " ... since "i" is less than the length
                of each array, it will only run as many times as the number of values
                in the array.
                In this case **2** times.
                */
            }
        }

        // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
        var divContainer = document.getElementById("showData");
        divContainer.innerHTML = "";
        divContainer.appendChild(table);
    }
</script>

</html>

到處都有評論,所以一定要閱讀它們並理解為什么它會這樣工作。 因為這也是一個學習的過程。 如果您有問題,請提出。

此代碼實現另一個 function 以創建水平格式。 請閱讀評論並嘗試理解它,以便將來對您有所幫助

<html>

<body>
    <input type="button" onclick="createHorizontal()" value="Create Table From JSON" />
    <p id="showData"></p>
    <div id="horizontal"></div>
</body>

<script>

    function createHorizontal(){
        var myBooks = JSON.parse(localStorage.getItem("quant"));
        console.log(myBooks);

        col_keys = Object.keys(myBooks);
        // Object.keys gets the keys of the object
        col_values = Object.values(myBooks);
        // Object.values gets the values in an object

        var final_array = [];
        /* Here is the final array that will hold all the data */

        for(var i = 0; i < col_keys.length; i++){
            var inner = [];
            // The inner array that will be pushed with a new value
            // after every loop

            inner.push("<div class='main'>");
            inner.push("<li>" + col_keys[i] + "</li>");
            for(var j = 0; j < col_values[0].length; j++){
                inner.push("<li>" + col_values[i][j] + "</li>");
            }
            inner.push("</div>");

            //The above code creates the html for each of the rows

            inner = inner.join("");
            // To remove the commas from the final array
            final_array.push(inner);
        }
        console.log(final_array);

        var elem = document.getElementById("horizontal");
        var final_div = [];

        final_div.push("<div class='container'>");
        for(var n = 0; n < final_array.length; n++){
            final_div.push(final_array[n]);
        }
        final_div.push("</div>");

        // The above code creates the html for the whole div block

        final_div = final_div.join("");
        // To remove the commas
        console.log(final_div);

        elem.innerHTML = "";
        elem.innerHTML = final_div;
    }
</script>
<style>
    .container {
        display: flex;
        flex-direction: column;
        /* Make the rows stack on top of each other */
    }

    .main {
        display: flex;
        flex-direction: row;
        /* Make the elements in the div stack side by side */
    }

    .main li {
        list-style-type: none;
        padding: 5px 10px;
        width: 50px;
    }

    .main li:first-of-type {
        font-weight: bold;
        background-color: #222222;
        color: #ffffff;
    }
</style>

</html>

它還使用CSS使元素以該格式顯示,否則看起來會有所不同。 我建議你分析和理解它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM