使用数据属性和jQuery对div排序 [英] Sort divs using data attributes and jQuery
问题描述
我是Java语言的新手,似乎找不到解决方案,因此,如果已经解决此问题,请原谅我.
i'm new to Javascript and can't seem to find a solution so please forgive me if this has already been answered.
我有一个div列表(可以说这些是不同颜色袜子的产品).我希望用户能够单击按钮并根据每个div的数据属性按价格和受欢迎程度对这些div进行排序,而无需使用数组.
I have a list of divs (lets say these are products of different colored socks). I want users to be able to click buttons and sort these divs by price and popularity based on data attributes of each div without using arrays.
这是我当前的JSFiddle: https://jsfiddle.net/4z97xffh/
Here is my current JSFiddle: https://jsfiddle.net/4z97xffh/
var divList = $(".listing-item");
function sortPrice(){
divList.sort(function(a, b){ return $(a).data("price")-$(b).data("price")});
$("#list").html(divList);}
function sortPopularity(){
divList.sort(function(a, b){ return $(a).data("popularity")-$(b).data("popularity")});
$("#list").html(divList);}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="sortPrice()">Sort by price Low -> High</button>
<button onclick="sortPopularity()">Sort by Popularity Low -> High</button>
<div id="list">
<div class="listing-item" data-price="4" data-popularity="4">[Red Socks] Price: $4 | Popularity: 3</div>
<div class="listing-item" data-price="2" data-popularity="2">[Blue Socks] Price: $2 | Popularity: 1</div>
<div class="listing-item" data-price="1" data-popularity="1">[Green Socks] Price: $1 | Popularity: 2</div>
<div class="listing-item" data-price="3" data-popularity="3">[Yellow Socks] Price: $3 | Popularity: 4</div>
</div>
推荐答案
问题不在于您的代码,而在于您的属性.您的人气值与<div>
内的值不匹配.
The problem is not with your code, but rather with your attributes. Your popularity values do not match the values inside the <div>
s.
下面是一个片段,其值与您的文本匹配:
Below is a snippet with the values matching your text:
var divList = $(".listing-item");
function sortPrice(){
divList.sort(function(a, b){ return $(a).data("price")-$(b).data("price")});
$("#list").html(divList);}
function sortPopularity(){
divList.sort(function(a, b){ return $(a).data("popularity")-$(b).data("popularity")});
$("#list").html(divList);}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="sortPrice()">Sort by price Low -> High</button>
<button onclick="sortPopularity()">Sort by Popularity Low -> High</button>
<div id="list">
<div class="listing-item" data-price="4" data-popularity="3">[Red Socks] Price: $4 | Popularity: 3</div>
<div class="listing-item" data-price="2" data-popularity="1">[Blue Socks] Price: $2 | Popularity: 1</div>
<div class="listing-item" data-price="1" data-popularity="2">[Green Socks] Price: $1 | Popularity: 2</div>
<div class="listing-item" data-price="3" data-popularity="4">[Yellow Socks] Price: $3 | Popularity: 4</div>
</div>
这篇关于使用数据属性和jQuery对div排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!