【发布时间】:2019-12-11 13:43:57
【问题描述】:
抱歉,如果这是一个新手问题,我正在学习 JS 和 jQuery。我试图在单击按钮后按 first_name 键对对象数组进行排序,但我没有成功。
我尝试使用 ajaxStyling 类获取 div。然后为 id 为 #btn-click 的按钮插入相邻的 html。然后我使用jQuery劫持点击并尝试使用newCourse.students(我的对象数组/在执行console.log时工作)的函数进行排序,但整个排序函数不起作用。我在控制台上没有收到错误,但文本不会排序。也许是我的回报?还是我需要再次追加?
$('#btn-click').on('click', (e) => {
e.preventDefault()
// console.log(newCourse.students)
newCourse.students.sort(function(a, b) {
// return a.first_name > b.first_name;
var nameA = a.first_name.toUpperCase();
var nameB = b.first_name.toUpperCase();
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
return 0;
});
newCourse.students
})
当我登录 newCourse.students 时得到什么
(3) [{…}, {…}, {…}]
0: {id: 11, first_name: "Stefan", last_name: "Candelaria", …}
1: {id: 12, first_name: "Robby", last_name: "Pasurin", …}
2: {id: 10, first_name: "Rafa", last_name: "Lopez", …}
length: 3
我的html。想在点击按钮后按名称排序,实现以下顺序 1.Rafa Lopez 2.Robby Pasurin 3.Stefan Candelaria ...而不是下面的顺序。
<div class="container">
<div class="ajaxStyling">
<a href="/courses/6" data-id="6"><h3 class="showText">Adobe Analytics 201 by Adam Greco</h3></a>
<p class="show_link">Stefan Candelaria</p>
<p class="show_link">Robby Pasurin</p>
<p class="show_link">Rafa Lopez</p>
</div>
<button id="btn-click">Click Me!</button>
</div>
【问题讨论】:
-
你认为
newCourse.students会做什么? -
您对数组进行排序,但不确定 HTML 与数组排序有何关系。如果你说它是颠倒的,听起来你会把 1 和 -1 的逻辑颠倒过来。
-
newCourse.students正在呼叫学生,这是课程的一个属性。我试过你的记录,但没有用:( -
看起来您在排序之前正在登录。 click 函数的最后一行没有做任何事情,但这就是你应该对数组做一些事情的地方。
标签: javascript jquery arrays sorting