Создание элементов DOM через createElements и querySelector - PullRequest
1 голос
/ 13 февраля 2020

Я получаю это сообщение об ошибке:

'ключ не определен'

Я пытаюсь создать новые узлы DOM, используя createElement, который содержит строки таблицы, клетки и данные. Строка должна содержать следующие ячейки: номер ISBN, заголовок, цена товара, количество и вычисленная общая стоимость (item price * quantity).

Добавить каждый новый узел к фрагменту DOM с помощью appendChild.

https://jsfiddle.net/51hLym9t/2/

Ответы [ 2 ]

2 голосов
/ 13 февраля 2020

Я вижу, вам не хватает атрибута id в теге <table>. Так что просто добавьте этот атрибут и заполните таблицу:

// Check to see if page is still loading. 
    if (document.readyState == 'loading') {
          // Still loading, so add an event listener to wait for it to finish.
         document.addEventListener('DOMContentLoaded', addData);
    } else {
          // DOM is already ready, so run the program!
          addData();  
    }  


    // Takes an object containing item data, and adds
    // the data to an existing table in the DOM
    function addData(){

        let books = {

            9781118876138 : { isbn : "9781118876138", 
                             title : "DATA SCIENCE & BIG DATA ANALYSIS", 
                             price : 60.00, 
                             quantity: 1 },

            9781107186125 : { isbn : "9781107186125", 
                             title : "PRINCIPLES OF DATABASE MANAGEMENT", 
                             price : 77.99, 
                             quantity: 1 },

            9781587205880 : { isbn : "9781587205880", 
                             title : "CCNA ROUTING & SWITCHING PORTABLE COMMAND GUIDE", 
                             price : 24.00, 
                             quantity: 2 },

            9781119288312 : { isbn : "9781119288312", 
                             title : "CCNA ROUTING AND SWITCHING : EXAM", 
                             price : 73.50, 
                             quantity: 2 },

            9781305078628 : { isbn : "9781305078628", 
                             title : "HANDS-ON MICROSOFT WINDOWS SERVER 2016", 
                             price : 108.75, 
                             quantity: 1 },

            9781541895386 : { isbn : "9781541895386", 
                             title : "INTRODUCTION TO WEB DEVE", 
                             price : 65.25, 
                             quantity: 1 },

            9781943872381 : { isbn : "9781943872381", 
                             title : "MURACH'S PHP AND MYSQL", 
                             price : 43.25, 
                             quantity: 1 },

            9780134167008 : { isbn : "9780134167008", 
                             title : "REVEL FOR LIANG JAVA ACCESS CARD", 
                             price : 86.75, 
                             quantity: 1 },
       };

      // Select the body of the table.
      let tableBody = document.querySelector("#groceries tbody");
      let groceryKeys = Object.keys(books) ;
      let groceryCount = groceryKeys.length ;
      let groceryValues = Object.values(books) ;
     
      // Create the temporary DOM fragment to hold our elements.
      let fragment = document.createDocumentFragment();
      let item ;
      let description ;
      let price ;
      let quantity ;
      let tr;
      let td;
      let text;
      // Loop through our groceries and build one table row for each grocery item.
      for (key in books ) {
          item= books[key];

          isbn = item.isbn;
          title = item.title;
          price = item.price;
          quantity= item.quantity;

          tr = document.createElement("tr");

          td = document.createElement("td");
          text = document.createTextNode(isbn);
          td.appendChild(text);
          tr.appendChild(td);
          
          td = document.createElement("td");
          text = document.createTextNode(title);
          td.appendChild(text);
          tr.appendChild(td);

          td = document.createElement("td");
          text = document.createTextNode(price);
          td.appendChild(text);
          tr.appendChild(td);

          td = document.createElement("td");
          text = document.createTextNode(quantity);
          td.appendChild(text);
          tr.appendChild(td);
          
          td = document.createElement("td");
          text = document.createTextNode(price * quantity);
          td.appendChild(text);
          tr.appendChild(td);

          // Add our table row to our DOM fragment.
          fragment.appendChild(tr);

      }
      // Add the DOM fragment to the end of the table body.
      tableBody.appendChild(fragment) ;
    }
<section class="">
    <h2>Purchased Items</h2>
    <table id="groceries">
        <thead>
            <tr>
                <th scope="col">ISBN</th>
                <th class="" scope="col">Title</th>
                <th class="price-heading" scope="col">Item Price</th>
                <th class="quantity" scope="col">Quantity</th>
                <th class="price-heading" scope="col">Total</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
        </tbody>
        <tfoot>
            <tr>
                <td colspan='5' id="sub-total" class="price-totals"></td>
                <td class="">Subtotal</td>
            </tr>
            <tr>
                <td colspan='5' id="tax-amount" class="price-totals"></td>
                <td class="">Tax</td>
            </tr>
            <tr>
                <td colspan='4'></td>
                <td id="total" class="price-totals total"></td>
                <td class="total">Total Cost</td>
            </tr>
        </tfoot>
    </table>
</section>
0 голосов
/ 13 февраля 2020

// Check to see if page is still loading. 
    if (document.readyState == 'loading') {
          // Still loading, so add an event listener to wait for it to finish.
         document.addEventListener('DOMContentLoaded', addData);
    } else {
          // DOM is already ready, so run the program!
          addData();  
    }  


    // Takes an object containing item data, and adds
    // the data to an existing table in the DOM
    function addData(){

        let books = {

            9781118876138 : { isbn : "9781118876138", 
                             title : "DATA SCIENCE & BIG DATA ANALYSIS", 
                             price : 60.00, 
                             quantity: 1 },

            9781107186125 : { isbn : "9781107186125", 
                             title : "PRINCIPLES OF DATABASE MANAGEMENT", 
                             price : 77.99, 
                             quantity: 1 },

            9781587205880 : { isbn : "9781587205880", 
                             title : "CCNA ROUTING & SWITCHING PORTABLE COMMAND GUIDE", 
                             price : 24.00, 
                             quantity: 2 },

            9781119288312 : { isbn : "9781119288312", 
                             title : "CCNA ROUTING AND SWITCHING : EXAM", 
                             price : 73.50, 
                             quantity: 2 },

            9781305078628 : { isbn : "9781305078628", 
                             title : "HANDS-ON MICROSOFT WINDOWS SERVER 2016", 
                             price : 108.75, 
                             quantity: 1 },

            9781541895386 : { isbn : "9781541895386", 
                             title : "INTRODUCTION TO WEB DEVE", 
                             price : 65.25, 
                             quantity: 1 },

            9781943872381 : { isbn : "9781943872381", 
                             title : "MURACH'S PHP AND MYSQL", 
                             price : 43.25, 
                             quantity: 1 },

            9780134167008 : { isbn : "9780134167008", 
                             title : "REVEL FOR LIANG JAVA ACCESS CARD", 
                             price : 86.75, 
                             quantity: 1 },
       };

      // Select the body of the table.
      let tableBody = document.querySelector("#groceries tbody");
      let groceryKeys = Object.keys(books) ;
      let groceryCount = groceryKeys.length ;
      let groceryValues = Object.values(books) ;
     
      // Create the temporary DOM fragment to hold our elements.
      let fragment = document.createDocumentFragment();
      let item ;
      let description ;
      let price ;
      let quantity ;
      let isbn ; 
      let title ;
      let tr;
      let td;
      let text;
      // Loop through our groceries and build one table row for each grocery item.
      for (let key in books ) {
          item= books[key];

          isbn = item.isbn;
          title = item.title;
          price = item.price;
          quantity= item.quantity;

          tr = document.createElement("tr");

          td = document.createElement("td");
          text = document.createTextNode(isbn);
          td.appendChild(text);
          tr.appendChild(td);
          
          td = document.createElement("td");
          text = document.createTextNode(title);
          td.appendChild(text);
          tr.appendChild(td);

          td = document.createElement("td");
          text = document.createTextNode(price);
          td.appendChild(text);
          tr.appendChild(td);

          td = document.createElement("td");
          text = document.createTextNode(quantity);
          td.appendChild(text);
          tr.appendChild(td);
          
          td = document.createElement("td");
          text = document.createTextNode(price * quantity);
          td.appendChild(text);
          tr.appendChild(td);

          // Add our table row to our DOM fragment.
          fragment.appendChild(tr);

      }
      // Add the DOM fragment to the end of the table body.
      tableBody.appendChild(fragment) ;
    }
<section class="">
    <h2>Purchased Items</h2>
    <table id="groceries">
        <thead>
            <tr>
                <th scope="col">ISBN</th>
                <th class="" scope="col">Title</th>
                <th class="price-heading" scope="col">Item Price</th>
                <th class="quantity" scope="col">Quantity</th>
                <th class="price-heading" scope="col">Total</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
        </tbody>
        <tfoot>
            <tr>
                <td colspan='5' id="sub-total" class="price-totals"></td>
                <td class="">Subtotal</td>
            </tr>
            <tr>
                <td colspan='5' id="tax-amount" class="price-totals"></td>
                <td class="">Tax</td>
            </tr>
            <tr>
                <td colspan='4'></td>
                <td id="total" class="price-totals total"></td>
                <td class="total">Total Cost</td>
            </tr>
        </tfoot>
    </table>
</section>
...