使用数据属性和javascript对div进行排序

时间:2016-07-20 00:26:20

标签: javascript html

我是Javascript的新手,似乎无法找到解决方案,所以请原谅我,如果这已经得到了解答。

我有一个div列表(假设这些是不同颜色袜子的产品)。我希望用户能够根据每个div的数据属性单击按钮并按价格和流行度对这些div进行排序,而不使用数组。

这是我目前的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 -&gt; High</button>
<button onclick="sortPopularity()">Sort by Popularity Low -&gt; 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>
  
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

问题不在于您的代码,而在于您的属性。您的受欢迎程度值与<div> s。

中的值不匹配

以下是与您的文字匹配的代码段:

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 -&gt; High</button>
<button onclick="sortPopularity()">Sort by Popularity Low -&gt; 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>