在jQuery中基于数据属性对div进行排序 [英] Sorting a div based on data attribute in jQuery

查看:55
本文介绍了在jQuery中基于数据属性对div进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我正在努力做到这一点,以便jQuery在单击按钮时对div进行排序,

Alright, I'm trying to make it so jQuery sorts the divs when a button is clicked,

假设列表看起来像这样,

Let's say the list looks like this,

<div class="wrapper">
  <div class="item" data-worth="720">Edgy</div>
  <div class="item" data-worth="420">Blaze</div>
  <div class="item" data-worth="666">Meme</div>
</div>

然后单击按钮后,我希望它吐出来,

Then after the button is clicked I want it to spit out,

   <div class="wrapper">
      <div class="item" data-worth="720">Edgy</div>
      <div class="item" data-worth="666">Meme</div>
      <div class="item" data-worth="420">Blaze</div>
    </div>

基本上将价值从低到高排序,重新排列所有内容并将其放回包装器中.

Basically sorting worth from low to high, rearanging everything and putting it back in the wrapper.

老实说,我对如何做到这一点一无所知,我想到了使用jQuery的 .each 函数,但随后我只能在顶部获得最高的价值,任何建议?

I'm honestly clueless on how I'd go on doing this, I thought of using jQuery's .each function but then I'd only be able to get highest value on the top, any suggestions?

推荐答案

根据包装器的 divs data('worth')排序,然后附加排序后的列表返回包装器:

Sort the wrapper's divs based on their data('worth'), then append the sorted list back to the wrapper:

$('button').click(function() {
  $('.wrapper div').sort(function(a, b) {
    return $(b).data('worth') - $(a).data('worth');
  }).appendTo('.wrapper');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Sort</button>
<div class="wrapper">
  <div class="item" data-worth="720">Edgy</div>
  <div class="item" data-worth="420">Blaze</div>
  <div class="item" data-worth="666">Meme</div>
</div>

这篇关于在jQuery中基于数据属性对div进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆