Есть несколько вещей, которые вы можете сделать со своим кодом.
Например:
1) Добавьте <thead>
и <tbody>
в вашу таблицу HTML, чтобы вам нужно было толькообновить тело при изменении данных.
2) Используйте async/await
для загрузки данных. Таким образом, вы можете легко поддерживать глобальное хранилище данных.
3) map
поверх вашего набора данных и возвращать шаблонный литерал ваших данных строки.
4) Добавить функции для многоразового кода.
// Add `async` to the enclosing function
$(document).ready(async function() {
const endpoint = 'https://api.jsonbin.io/b/5dc2e815c9b247772abb67b2/1';
// Await your data. `getJSON` is a promise-like structure so you can use `await` on it
// We can destructure out the movies property from the data
const { movies } = await $.getJSON(endpoint);
// Because you're reusing some code you can put it in a function and call it
// with a new set of data each time
function getTableHTML(movies) {
// `map` will return a new array so make sure you
// `join` it up at the end to make one complete HTML string
return $.map(movies, function(movie, index) {
return `
<tr>
<td>${movie.title}</td>
<td>${movie['imdb-id']}</td>
<td>${movie.rank}</td>
<td>${movie.rating}</td>
<td>${movie['rating-count']}</td>
</tr>
`
}).join('');
}
// Get the movie HTML
const tableHTML = getTableHTML(movies);
// Add it to the movies table body
$('#movie_table tbody').html(tableHTML);
// I've separate out the sort function
function sortMovies(movies) {
return movies.sort(function(a, b) {
return a.title < b.title ? -1 : 1;
});
}
$("#btn-sort").click(function(data) {
// Now you simply need to pass in the movies
const sortedMovies = sortMovies(movies);
// And pass the sorted movies into your getTableHTML function
const tableHTML = getTableHTML(sortedMovies);
// Then update the table body again
$('#movie_table tbody').html(tableHTML);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="table-responsive">
<h1>TOP MOVIES</h1>
<button id="btn-sort">Sort</button>
<br />
<table class="table table-bordered table-striped" id="movie_table">
<thead>
<tr>
<th>Title</th>
<th>IMDB-ID</th>
<th>RANK</th>
<th>RATING</th>
<th>RATING-COUNT</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>