按HTML数据属性排序数组?

时间:2016-04-12 05:19:10

标签: javascript jquery arrays sorting local-storage

我正在尝试学习本地存储空间。我有五个链接,每个链接都有一个data-date属性,我希望它们使用该属性进行排序。我尝试了很多方法,但似乎没有任何效果。根据我的理解,我应该在排序之前进行解析,但它对我没有用。我一定做错了,因为我不知道怎么做。

这是我的HTML:

<div id="div1">
    <input id='clearHistory' type='button' value='Remove All History' />
    <input id='showHistory' type='button' value='Show History' />
    <ul id='history'>
      <li>
        <a class='date' href="#aa" data-date="November 12, 2001 03:24:00">Link 1</a>
      </li>
      <li>
        <a class='date' href="#bb" data-date="August 4, 1993 03:24:00">Link 2</a>
      </li>
      <li>
        <a class='date' href="#cc" data-date="October 17, 1995 03:24:00">Link 3</a>
      </li>
      <li>
        <a class='date' href="#dd" data-date="December 1, 2010 03:24:00">Link 4</a>
      </li>
      <li>
        <a class='date' href="#ee" data-date="August 17, 2004 03:24:00">Link 5</a>
      </li>
    </ul>
  </div>

  <p>Click on 'Show History' to see the 'user history'.</p>
  <ul id='storedHistory'></ul>

我的JavaScript:

$(document).ready(function() {
  var storedHistory = document.getElementById('storedHistory');

  Storage.prototype.setObject = function(key, value) {
    this.setItem(key, JSON.stringify(value));
  };

  Storage.prototype.getObject = function(key) {
    var value = this.getItem(key);
    return value && JSON.parse(value);
  };

  //function sortDatesAscending(a, b) { return a.valueOf() - b.valueOf(); } function sortDatesDescending(a, b) { return b.valueOf() - a.valueOf(); }

  function sortLinkDatesAscending(obj1, obj2) {
    return obj1.date.valueOf() - obj2.date.valueOf();
  }

  function sortLinkDatesDescending(obj1, obj2) {
    return obj2.date.valueOf() - obj1.date.valueOf();
  }

  var history = {
    items: []
  };

  // Get each anchor and retrieve its date and link. Add to an object and add that object to the history's array Sort by ascending. Add to local storage.
  $('ul > li > a').click(function(e) {
    var date = $(this).attr('data-date');
    var listData = {
      link: $(this).attr("href"),
      date: date
    };
    history.items.push(listData);
    window.localStorage.setObject("history", history);
  });

  /* Remove items from local storage */
  $('#clearHistory').click(function() {
    window.localStorage.clear();
  });

  /* Retrieve items from local storage and add to stored history unordered list */
  $('#showHistory').click(function() {
    console.log(window.localStorage);
    var listHistory = localStorage.getObject('history');
    var counter = 1;
    for (var i = 0; i < listHistory.items.length; i++) {
      $("#storedHistory").append('<li>' + counter + '. Link: ' + listHistory.items[i].link + '<br>' + 'Date: ' + listHistory.items[i].date + '</li>');
      counter++;
    }
  });
});

这是jsfiddle:https://jsfiddle.net/fLLsfd5j/2/

2 个答案:

答案 0 :(得分:1)

尝试这个进行排序! (http://trentrichardson.com/2013/12/16/sort-dom-elements-jquery/

var $history = $('#history li'),
        $historyA = $history.children();
        $historyA.sort(function (a, b) {
            var an = Date.parse(a.getAttribute('data-date')).valueOf(),
            bn = Date.parse(b.getAttribute('data-date')).valueOf();
            if (an > bn) {
                return 1;
            }
            if (an < bn) {
                return -1;
            }
            return 0;
        });
        $('#history').empty();
        $.each($historyA, function () {
            $('#history').append($('<li>').html(this));
        });

答案 1 :(得分:0)

我想这应该可以胜任你的工作

function getHistory(){
  var as = document.querySelectorAll(".date"); // get elements with date class
  Array.prototype.map.call(as, e => e.cloneNode(true)) //clone them into an array and sort
                 .sort((p,c) => Date.parse(p.dataset.date)<=Date.parse(c.dataset.date) ? -1 : 1)
                 .forEach((e,i) => as[i].parentNode.replaceChild(e, as[i]));
}
showHistory.onclick = getHistory; //add "click" eL to the DOM element with showHistory id

http://jsbin.com/yoraqusora/2/edit?js,console,output