gpt4 book ai didi

jquery - 如何通过jquery按两个不同的参数对div进行排序

转载 作者:行者123 更新时间:2023-12-01 07:49:47 26 4
gpt4 key购买 nike

我的页面中有以下动态来自数据库的内容。我的div结构是这样的:

<div class="status_quotes" data-quote="19" data-status="certified"></div>
<div class="status_quotes" data-quote="15" data-status="un_certified"></div>
<div class="status_quotes" data-quote="8" data-status="un_certified"></div>
<div class="status_quotes" data-quote="5" data-status="certified"></div>
<div class="status_quotes" data-quote="14" data-status="un_certified"></div>
<div class="status_quotes" data-quote="9" data-status="certified"></div>

我希望它首先以这种方式排序,我将显示所有“已认证”数据状态 div,然后显示所有“未认证”,但我也希望它按“数据引用”排序数字按升序排列。生成的 div 将显示如下:

// first the certified quotes sorted with "data-quote"
<div class="status_quotes" data-quote="5" data-status="certified"></div>
<div class="status_quotes" data-quote="9" data-status="certified"></div>
<div class="status_quotes" data-quote="19" data-status="certified"></div>
// uncertified quotes sorted with "data-quote"
<div class="status_quotes" data-quote="8" data-status="un_certified"></div>
<div class="status_quotes" data-quote="14" data-status="un_certified"></div>
<div class="status_quotes" data-quote="15" data-status="un_certified"></div>

如有任何帮助,我们将不胜感激。提前致谢

最佳答案

我将代码更改为片段,并添加 orderByThenBy 来抽象排序逻辑,并且我仍然保留之前的旧代码

var $divs = $('div.status_quotes');
var orderByThenBy = [
{ "attr": 'data-status', 'typeFunc': null },
{ "attr": 'data-quote', 'typeFunc':function (v) { return parseInt(v); } }
];
$divs.sort(function (x, y) {
for (var i = 0; i < orderByThenBy.length; i++) {
var vx = $(x).attr(orderByThenBy[i].attr);
var vy = $(y).attr(orderByThenBy[i].attr);
var typeFunc = orderByThenBy[i].typeFunc;
if (typeFunc != null) {
vx = typeFunc(vx);
vy = typeFunc(vy);
}
if (vx !== vy) {
return vx > vy ? 1 : -1;
}
}
return 0;
});
//$divs.sort(function (x, y) {
// var statusX = $(x).attr("data-status");
// var statusY = $(y).attr("data-status");
// if (statusX == statusY) {
// var quoteX = parseInt($(x).attr("data-quote"));
// var quoteY = parseInt($(y).attr("data-quote"));
// return quoteX > quoteY ? 1 : -1;
// }
// else {
// return statusX > statusY ? 1 : -1;
// }
//});
$divs.each(function (i, n) {
console.info(n);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="status_quotes" data-quote="19" data-status="certified"></div>
<div class="status_quotes" data-quote="15" data-status="un_certified"></div>
<div class="status_quotes" data-quote="8" data-status="un_certified"></div>
<div class="status_quotes" data-quote="5" data-status="certified"></div>
<div class="status_quotes" data-quote="14" data-status="un_certified"></div>
<div class="status_quotes" data-quote="9" data-status="certified"></div>

关于jquery - 如何通过jquery按两个不同的参数对div进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31342710/

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