В таблице последняя запись идет последней. Я хочу, чтобы последние записи были вверху таблицы. Как это сделать? - PullRequest
0 голосов
/ 12 июля 2020

У меня есть форма, в которой, если пользователь что-то публикует, это будет показано в таблице. Я использую для этого базу данных firebase realtime. В настоящее время последние записи отображаются в последней части таблицы. Я хочу, чтобы последние записи отображались вверху таблицы. Последние записи должны располагаться первыми, а старые записи - последними.

// Initialize Firebase
var config = {
  //mycofig
};
firebase.initializeApp(config);

var database = firebase.database();
var ref = database.ref("Registrations");

ref.on("value", function(snapshot) {
  snapshot.forEach(function(childSnapshot) {
    var data = childSnapshot.val();
    var childKey = childSnapshot.key;
    var childData = childSnapshot.val();
  });
  var database = firebase.database();
  database.ref("Registrations").once("value", function(snapshot) {
    if (snapshot.exists()) {
      var content = "";
      snapshot.forEach(function(data) {
        var val = data.val();
        content += "<tr>";
        content += "<td>" + val.name + "</td>";
        content += "<td>" + val.business + "</td>";
        content += "<td>" + val.phone + "</td>";
        content += "<td>" + val.area + "</td>";
        content += "<td>" + val.category + "</td>";
        content += "</tr>";
      });
      $("#ex-table").append(content);
    }
  });
});
table {
  width: 100%;
  border-collapse: collapse;
}


/* Zebra striping */

tr:nth-of-type(odd) {
  background: #eee;
}

th {
  background: #333;
  color: white;
  font-weight: bold;
}

td,
th {
  padding: 6px;
  border: 1px solid #ccc;
  text-align: left;
}

@media only screen and (max-width: 760px),
(min-device-width: 768px) and (max-device-width: 1024px) {
  /* Force table to not be like tables anymore */
  table,
  thead,
  tbody,
  th,
  td,
  tr {
    display: block;
  }
  /* Hide table headers (but not display: none;, for accessibility) */
  thead tr {
    position: absolute;
    top: -9999px;
    left: -9999px;
  }
  tr {
    border: 1px solid #ccc;
  }
  td {
    /* Behave  like a "row" */
    border: none;
    border-bottom: 1px solid #eee;
    position: relative;
    padding-left: 50%;
  }
  td:before {
    /* Now like a table header */
    position: absolute;
    /* Top/left values mimic padding */
    top: 6px;
    left: 6px;
    width: 45%;
    padding-right: 10px;
    white-space: nowrap;
  }
  /*
Label the data
*/
  td:nth-of-type(1):before {
    content: "Name";
  }
  td:nth-of-type(2):before {
    content: "Location";
  }
  td:nth-of-type(3):before {
    content: "Rent p/m";
  }
  td:nth-of-type(4):before {
    content: "BHK/Rooms";
  }
  td:nth-of-type(5):before {
    content: "Total Persons";
  }
  td:nth-of-type(6):before {
    content: "Phone no";
  }
  td:nth-of-type(7):before {
    content: "Other Details";
  }
  td:nth-of-type(8):before {
    content: "Posting Date";
  }
}

</style>
<table id="ex-table">
  <thead>
    <tr>
      <th>Name</th>
      <th>Business name</th>
      <th>Phone no</th>
      <th>Area</th>
      <th>Category</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>

Ответы [ 2 ]

0 голосов
/ 12 июля 2020

Ваша проблема заключается в том, что вы помещаете элементы в конец таблицы после построения строки html - согласно следующему

 $("#ex-table").append(content);

Если вы поменяете местами это на «добавить» - это вставит новый элемент в начало таблицы согласно следующему:

 $("#ex-table").prepend(content);

Следовательно, последняя строка, добавленная в таблицу, будет первой строкой таблицы. Вот ссылка на документацию - https://api.jquery.com/prepend/

Тем не менее, я бы манипулировал считываемыми данными и менял их так, чтобы данные соответствовали порядку в ожидаемой таблице.

0 голосов
/ 12 июля 2020

flex-direction: column-reverse; поместит последние элементы таблицы на первое место. Добавьте это css в таблицу, в которой вы хотите, чтобы последние элементы были на первом месте:

#ex-table{
  display: flex;
  flex-direction: column-reverse;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...