【发布时间】:2016-02-24 08:05:54
【问题描述】:
我正在尝试编写代码以使用 ajax 调用显示表格并在单击按钮时对列进行排序。似乎我在排序功能中出错但无法解决它,整个列被年龄的最小值替换。我对显示部分也有疑问。
这是我的代码
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<link rel="stylesheet" href="http.css" >
</head>
<title>
</title>
<body>
<table id="link" border="1">
<thead>
<tr>
<td>Name</td>
<td>Age</td>
<td>Place</td>
</tr>
</thead>
</table>
<script>
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
var obj = JSON.parse(req.responseText);
parsedfun(obj);
}
};
req.open("GET", "xml.txt");
req.send();
function parsedfun(obj) {
var out = "";
for (var i = 0; i < obj.length; i++) {
out = out + '<tr><td class="namesort">' + obj[i].name + '</td><td class="agesort">' + obj[i].age + '</td><td class="placesort">' + obj[i].place + '</td></tr>';
$("#link").html(out);
$(".clk").click(function() {
$.getJSON("xml.txt", function(obj) {
$("td").each(function(index, value) {
obj.sort(function(a, b) {
if (a.age < b.age) {
return 1;
} else {
return -1;
}
});
$(".agesort").html(obj[index].age);
});
});
});
}
}
</script>
<button class="clk">sort the age</button>
<div class="division">
</div>
</body>
</html>
这里是“xml.txt”文件
[{
"name": "x",
"age": 21,
"place": "Hyderabad"
}, {
"name": "y",
"age": 28,
"place": "Chennai"
}, {
"name": "z",
"age": 20,
"place": "Coimbatore"
}, {
"name": "a",
"age": 19,
"place": "Kolkata"
}, {
"name": "b",
"age": 22,
"place": "Mumbai"
}, {
"name": "c",
"age": 16,
"place": "Mangalore"
}]
【问题讨论】:
-
旁注:如果年龄相同,比较函数应该返回
0而不是-1。
标签: javascript jquery json