简体   繁体   中英

JQuery sorting DIV by content

I am using the following code to sort DIV content by date and title.

It works well, but for date I want to sort it with newest first - at the moment it puts the newest last.

function sortUsingNestedText(parent, childSelector, keySelector) {
var items = parent.children(childSelector).sort(function(a, b) {
    var vA = jQuery(keySelector, a).text();
    var vB = jQuery(keySelector, b).text();
    return (vA < vB) ? -1 : (vA > vB) ? 1 : 0;
});
parent.append(items);
}

/* setup sort attributes */
jQuery('#sDate').data("sortKey", "span.date");
jQuery('#sStyle').data("sortKey", "span.title");


/* sort on button click */
jQuery("button.btnSort").click(function() {
sortUsingNestedText(jQuery('.sort-div'), "div", 
jQuery(this).data("sortKey"));
});

How can I change the order for date only (#sPrice)

Add a parser on the selector in a conditional in the sort callback.

function sortUsingNestedText(parent, childSelector, keySelector) {
  var items = parent.children(childSelector).sort(function(a, b) { 

    var vA = jQuery(keySelector, a).text();
    var vB = jQuery(keySelector, b).text();

    // date sorting
    if(keySelector.indexOf('.date') >-1){
       return new Date(vB) - new Date(vA);
    }else{
       return (vA < vB) ? -1 : (vA > vB) ? 1 : 0;
    }
  });
  parent.append(items);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM