Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/432.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用jQuery对问题进行排序_Javascript_Jquery_Sorting - Fatal编程技术网

Javascript 使用jQuery对问题进行排序

Javascript 使用jQuery对问题进行排序,javascript,jquery,sorting,Javascript,Jquery,Sorting,这是我的html <div class="products-grid"> <div data-sort="3" class="swiper-slide">Test</div> <div data-sort="1" class="swiper-slide">Test</div> <div data-sort="2" class="swiper-slide">Test</div> </d

这是我的html

<div class="products-grid">
    <div data-sort="3" class="swiper-slide">Test</div>
    <div data-sort="1" class="swiper-slide">Test</div>
    <div data-sort="2" class="swiper-slide">Test</div>
</div>

它不起作用。我想在数据排序属性之后对其进行排序。有人能帮我吗?

您需要将排序元素添加到DOM中

jQuery(文档).ready(函数(){
函数getSorted(选择器、属性名){
返回jQuery(选择器).toArray().sort(函数(a,b){
var aVal=parseInt(a.getAttribute(attrName)),
bVal=parseInt(b.getAttribute(attrName));
返回aVal-bVal;
});
}
var sortedElements=getSorted('.products grid.swiper slide','data sort');
jQuery(“.products grid”).append(sortedElements);
});

测试3
测试1
测试2

这是因为您正在对元素数组进行排序,而不是对DOM中的元素进行排序

jQuery(文档).ready(函数(){
函数getSorted(选择器、属性名){
返回jQuery(jQuery(selector).toArray().sort(函数a,b){
var aVal=parseInt(a.getAttribute(attrName)),
bVal=parseInt(b.getAttribute(attrName));
返回aVal-bVal;
}));
}
$('.products grid').html(getSorted('.products grid.swiper slide','data sort'));
});

测试3
测试1
测试2

展开
getSorted
jQuery()函数返回值
jQuery( document ).ready(function() {
    function getSorted(selector, attrName) {
        return jQuery(jQuery(selector).toArray().sort(function(a, b){
            var aVal = parseInt(a.getAttribute(attrName)),
                bVal = parseInt(b.getAttribute(attrName));
            return aVal - bVal;
        }));
    }
    getSorted('.products-grid .swiper-slide', 'data-sort');
});