gpt4 book ai didi

javascript - 使用javascript按不同属性排序

转载 作者:行者123 更新时间:2023-11-30 00:23:09 25 4
gpt4 key购买 nike

我有来自网络服务的以下 json

    var homes = [
{
"h_id": "3",
"city": "Dallas",
"state": "TX",
"zip": "75201",
"price": "162500",
"createdOn": "2015-08-31 00:35:14"
}, {
"h_id": "4",
"city": "Bevery Hills",
"state": "CA",
"zip": "90210",
"price": "319250",
"createdOn": "2015-08-31 14:35:14"
}, {
"h_id": "5",
"city": "New York",
"state": "NY",
"zip": "00010",
"price": "962500",
"createdOn": "2015-08-31 13:35:14"
}
];

我使用 ng-repeat 在 div (h_id) 中显示它。我知道如何使用 orderBy 进行排序。但这里我有一个 html select dropdpwn 列表。单击我想按新到旧、旧到新、价格和 h_id 排序。

我如何创建一个 javascript 函数来获得这种类型的功能?

最佳答案

试试这个...

<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<html>
<head>
<script type="text/javascript">
var homes = [
{
"h_id": "3",
"city": "Dallas",
"state": "TX",
"zip": "75201",
"price": "162500",
"createdOn": "2015-08-31 00:35:14"
}, {
"h_id": "1",
"city": "Bevery Hills",
"state": "CA",
"zip": "90210",
"price": "319250",
"createdOn": "2015-08-31 14:35:14"
}, {
"h_id": "5",
"city": "New York",
"state": "NY",
"zip": "00010",
"price": "1",
"createdOn": "2015-08-31 13:35:14"
}
];
function changeFunc() {

var selectBox = document.getElementById("selectBox");
var selectedValue = selectBox.options[selectBox.selectedIndex].value.trim();
alert(selectedValue);

var sort_by = function(field, reverse, primer){
var key = function (x) {return primer ? primer(x[field]) : x[field]};

return function (a,b) {
var A = key(a), B = key(b);
return ( (A < B) ? -1 : ((A > B) ? 1 : 0) ) * [-1,1][+!!reverse];
}
}

// Sort by price high to low
homes.sort(sort_by(selectedValue, true));
var u1 = document.getElementById('u1');
$(".remove").remove();
for (var i=0; i<homes.length; i++) {
u1.innerHTML += '<li class="remove">- '+homes[i].price+', '+homes[i].city+'</li>';
}

}

</script>
</head>
<body>
To sort or not to sort, that is the question.
<h3>By price asc</h3>
<ul id="u1" style="margin-bottom: 20px;"></ul>

<select id="selectBox" onchange="changeFunc();">
<option>Select option</option>
<option value="h_id">h_id</option>
<option value="price">price</option>
<option value="city">city</option>
</select>
</body>
</html>

演示:http://js.do/code/66972

关于javascript - 使用javascript按不同属性排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32430767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com