我有这个数据库和排序功能。排序完成到一个html表,该表从database.json文件中获取数据。问题在于,排序时会根据索引而不是要求的位置名称对它们进行排序。例如,在这种情况下,它将仅反转第一组数据和最后一组数据。 (1,2,3)->(3,2,1)
请帮助...
数据库
[
{
"title": "Great big event",
"location": "Grand plaza"
},
{
"title": "Cross cultural food tasting",
"location": "Melius Restaurant",
"date": "18 December 2018",
"time": "8 PM",
"description" : "Food tasting event where you can enjoy a mix of 10 famous cuisines"
},
{
"title": "Small dining event",
"location": "Cafe Il diroma",
"date": "10 February 2019",
"time": "6 AM",
"description": "The perfect place for casual dinners"
}
]
排序功能
location.sort(function(a, b){
if(a.location < b.location) { return -1; }
if(a.location > b.location) { return 1; }
return 0;
})
</script>
<body>
<div class="show-inline-block">
<button onclick="location.sort(a,b)" class="button button2">Sort table</button>
</div>
<div id="result"></div>
</body>
更新: 对使用来自database.json的数据制成的HTML表进行排序
<div class="table-responsive">
<table class="table table-striped" id="myTable" >
<thead>
<tr>
% for k in displaykeys:
<th scope="col" style="padding-left:30px">{{k.title()}}</th>
% end # Usual python indention to structure code does not work in .tpl files - "end" is used instead to end a block
</tr>
</thead>
<tbody>
% for i, d in enumerate(displaydata): # displaydata is expected to be a list of dictionaries
% link_url = "/events/" + str(i + 1) # relative url to detailed view
<tr>
% for k in displaykeys: # Go thru the keys in the same order as for the headline row
<td style="padding-left:30px"><a href="{{link_url}}" alt="See details">{{displaydata[i][k]}}</a></td>
% end # Usual python indention to structure code does not work in .tpl files - "end" is used instead to end a block
</tr>
% end
</tbody>
</table>
</div>
答案 0 :(得分:0)
您的排序代码不是问题。问题在于整体代码的结构。
location
是一个全局名称,而不是您应该重新定义的名称。另外,在您的HTML onclick
中,您传递的是a
和b
,它们都没有值且未定义。
您需要为按钮的click
事件设置回调函数,然后在该函数中执行排序。
请参见下面的内嵌评论:
// Don't use global names as identifiers. "location" is a global.
let loc = [
{
"title": "Great big event",
"location": "Grand plaza"
},
{
"title": "Cross cultural food tasting",
"location": "Melius Restaurant",
"date": "18 December 2018",
"time": "8 PM",
"description" : "Food tasting event where you can enjoy a mix of 10 famous cuisines"
},
{
"title": "Small dining event",
"location": "Cafe Il diroma",
"date": "10 February 2019",
"time": "6 AM",
"description": "The perfect place for casual dinners"
}
];
// Get your DOM references
let btn = document.querySelector("button");
// Set up event handling in JavaScript, not HTML
btn.addEventListener("click", sort);
// Set up a function that can be called when the button is clicked
function sort(){
// Do your sort in that function
loc.sort(function(a, b){
if(a.location < b.location) { return -1; }
if(a.location > b.location) { return 1; }
return 0;
});
// Show results
console.log(loc);
}
<div class="show-inline-block">
<button class="button button2">Sort table</button>
</div>