Je montre les données JSON sous forme de tableau sur la page HTML, je veux trier les données sur le bouton, cliquez par ordre alphabétique (titre). Après avoir cliqué sur un bouton, j'ai reçu une erreur indiquant que data.sort n'est pas défini ou data.sort n'est pas une fonction. La page n'a pas besoin d'être rechargée pour la fonction de tri. Je supprime la tête du code pour le raccourcir
<!DOCTYPE html>
<html>
<body>
<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">
<tr>
<th>Title</th>
<th>IMDB-ID</th>
<th>RANK</th>
<th>RATING</th>
<th>RATING-COUNT</th>
</tr>
</table>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function() {
$.getJSON("https://api.jsonbin.io/b/5dc2e815c9b247772abb67b2/1", function(data) {
var movie_data = '';
$.each(data.movies, function(key, value) {
movie_data += '<tr>';
movie_data += '<td>' + value.title + '</td>';
movie_data += '<td>' + value['imdb-id'] + '</td>';
movie_data += '<td>' + value.rank + '</td>';
movie_data += '<td>' + value.rating + '</td>';
movie_data += '<td>' + value['rating-count'] + '</td>';
movie_data += '<tr>';
});
$('#movie_table').append(movie_data);
});
$("#btn-sort").click(function(data) {
data.sort(function(a,b) {
return a.title < b.title ? -1 : 1;
});
var movie_data = '';
$.each(data.movies, function(key, value) {
movie_data += '<tr>';
movie_data += '<td>' + value.title + '</td>';
movie_data += '<td>' + value['imdb-id'] + '</td>';
movie_data += '<td>' + value.rank + '</td>';
movie_data += '<td>' + value.rating + '</td>';
movie_data += '<td>' + value['rating-count'] + '</td>';
movie_data += '<tr>';
});
$('#movie_table').slice(1).remove(); // To remove everything except first row
$('#movie_table').append(movie_data);
});
});
</script>
1 réponse
Il y a un certain nombre de choses que vous pouvez faire avec votre code.
Par exemple:
1) Ajoutez <thead>
et <tbody>
à votre tableau HTML afin de n'avoir besoin de mettre à jour le corps que lorsque les données changent.
2) Utilisation asynchrone / attendre pour charger les données. De cette façon, vous pouvez facilement gérer un magasin de données mondial.
3) carte sur votre jeu de données et renvoyer un modèle littéral de vos données de ligne.
4) Ajoutez des fonctions pour le code réutilisable.
// 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>
De nouvelles questions
javascript
Pour des questions concernant la programmation dans ECMAScript (JavaScript / JS) et ses divers dialectes / implémentations (hors ActionScript). Veuillez inclure toutes les balises pertinentes dans votre question; par exemple, [node.js], [jquery], [json], etc.