Добавить головы к столу программно - PullRequest
0 голосов
/ 01 августа 2020

Я могу получить json данных и программно поместить их в таблицу. Здесь у вас есть код, который вы можете запустить. Моя проблема в том, как программно добавлять головы? Здесь вы можете найти отлично работающий код LINK Codepen Code

function search() {
    var queryURL = "https://jsonplaceholder.typicode.com/users";

    fetch(queryURL)
            .then(response=> response.json())
            .then(data=>displayUsersAsATable(data))
               .catch(function (error) {
                console.log('Error during fetch: ' + error.message);
            });
}

function displayUsersAsATable(data) {
 
    var usersDiv = document.querySelector("#users");
    usersDiv.innerHTML = "";

    // creates and populate the table with users
    var table = document.createElement("table");

    data.forEach(function (currentUser) {
  
      var myhead = table.createTHead();
      myhead.innerHTML = "Table Heading"
      
      var mycaption = table.createCaption();
        mycaption.innerHTML = "Table Caption"
  
        var row = table.insertRow();
        var nameCell = row.insertCell();
        nameCell.innerHTML = currentUser.email;
        var cityCell = row.insertCell();
        cityCell.innerHTML = currentUser.address.city;
    });
    
        // adds the table to the div
        usersDiv.appendChild(table);
    } 

1 Ответ

0 голосов
/ 01 августа 2020

Согласно этой ссылке, мы не можем использовать API таблиц, например insertCell , для вставки тегов <th> в HTML. Но это может быть достигнуто программно, создав элемент с помощью document.createElement и вставив его.

В коде, который вы разделяете, создание заголовка таблицы включено в l oop, что приведет к созданию заголовка для каждого данные. Поэтому я переместил создание головы за пределы l oop, предполагая, что это так.

Связанный фрагмент:

   var myhead = table.createTHead();
   var headRow = myhead.insertRow();
   var emailHead = document.createElement('th');
   var nameHead = emailHead.cloneNode();
   headRow.appendChild(emailHead);
   headRow.appendChild(nameHead);
   emailHead.innerHTML = 'Email';
   nameHead.innerHTML = 'Name';

Рабочая демонстрация:

function search() {
    var queryURL = "https://jsonplaceholder.typicode.com/users";

    fetch(queryURL)
            .then(response=> response.json())
          //arrow function by Mauro - works fine!
            .then(data=>displayUsersAsATable(data))
               .catch(function (error) {
                console.log('Error during fetch: ' + error.message);
            });
}

//questa è una variazione

function displayUsersAsATable(data) {
    // users is a JavaScript object

    // empty the div that contains the results
    var usersDiv = document.querySelector("#users");
    usersDiv.innerHTML = "";
  
    // creates and populate the table with users
    var table = document.createElement("table");
    var mycaption = table.createCaption();
    mycaption.innerHTML = "Table Caption"
    
    //Creating and populating table header.
    var myhead = table.createTHead();
    var headRow = myhead.insertRow();
    var emailHead = document.createElement('th');
    var nameHead = emailHead.cloneNode();
    headRow.appendChild(emailHead);
    headRow.appendChild(nameHead);
    emailHead.innerHTML = 'Email';
    nameHead.innerHTML = 'Name';
  
    var tableBody = table.createTBody();
  
    // iterate on the array of users
    data.forEach(function (currentUser) {
      //inserimento dei titoli della colonna programmaticamente
        // creates a row
        var row = tableBody.insertRow();
        // insert cells in the row
        var nameCell = row.insertCell();
        nameCell.innerHTML = currentUser.email;
        var cityCell = row.insertCell();
        cityCell.innerHTML = currentUser.address.city;
    });

    // adds the table to the div
    usersDiv.appendChild(table);
} 
table {
  margin-top: 20px;
}
table, tr, td {
  border: 1px solid;
background-color: rgb(200, 200, 100);
} 
<head>
<title>Working with remote data</title>
  <meta charset="utf-8"/>
  <!-- Polyfill in case your browser does not support the fetch API -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/0.10.1/fetch.js"></script>

</head>
<body>
  <button onclick="search();">Get remote list of users' names and emails using the fetch API</button>
  <div id="users"></div>
</body>
...