javascript - How to sort by name through Jquery?
问题描述
I am just using Jquery
to create a list of my products in my html document from the json
data. I was just trying to be able to sort my products through clicking my heading name which will sort my products by alphabetical order.
I have researched on how to do this but cant find/understand how i can do this through using my data from json
.
Any help is appreciated. Thanks
function drawPage() {
$.get('/products', function (data) {
console.log(data);
var prod = data.products;
for(var i=0; i<prod.length; i++){
var el = document.createElement('P');
el.innerHTML = prod[i].name;
$('#app').append(el);
}
})
}
document.addEventListener('load', drawPage());
解决方案
var prod = [
{name: "truck", price: "20000"},
{name: "car", price: "50000"},
{name: "bus", price: "30000"}]
function SortByName(x,y) {
return ((x.name == y.name) ? 0 : ((x.name > y.name) ? 1 : -1 ));
}
$(function () {
prod.sort(SortByName);
console.log(prod)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
推荐阅读
- javascript - 我生成了 2 个等长 (15) 的数组,每个位置有 4 个可能的字母可供选择 - 为什么它们返回 53% 到 87% 的相似度?
- matlab - 象征性地评估梯度矩阵
- css - CSS 中的渐变在 React 中不适合我
- jquery - 从行自定义属性中获取 id
- sql - 在 SQL 中合并后删除重复项
- vue.js - 在 vue js 中导入和导出变量
- python - 如何在第二个屏幕上将 MDTextField 输入与 Label 的文本绑定
- javascript - 如何将登录令牌传递给聊天机器人以实现单点登录
- css - Bootstrap:如何使封面模板的导航栏响应(汉堡菜单)?
- typescript - 打字稿 - 需要 N 长度数组中的单个文字值