【问题标题】:On toggle, show a class and hide the rest whilst in alphabetical order.在切换时,按字母顺序显示一个类并隐藏其余部分。
【发布时间】:2015-07-13 15:38:34
【问题描述】:

我有一些 div 元素,我希望能够根据它们的子元素对其进行排序。

我使用没有任何插件的 jQuery 寻找显示某个类同时隐藏其余部分的东西。我遇到了这个Toggle multiple Div names/content by one button click,它对这样做非常有帮助。但是,我还希望排序的元素也按字母顺序显示,具体取决于指定的类。

我尝试使用这个:Jquery - sort DIV's by innerHTML of children。但是,它似乎不起作用。任何帮助将不胜感激!

这是我目前所拥有的:http://jsfiddle.net/y11hr6d8/

这是 jQuery:

$(function() {

var $articles = $('.article');

$(".langButton").click(function() {
    var language = $(this).attr("data-language");
    $articles.hide(); // Hide them all
    $("." + language).show(); // than show the needed ones
});
});

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

$('#sEthnicity').data("sortKey", "span.article ethnicity");
$('#sGender').data("sortKey", "span.article gender");
$('#sPet').data("sortKey", "span.article pet");
$('#sSubject').data("sortKey", "span.article subject");

$("button.langButton").click(function() {
    sortUsingNestedText($('#sortThis'), "div", $(this).data("sortKey"));
});

【问题讨论】:

    标签: javascript jquery sorting


    【解决方案1】:
        $(function() {
            var $articles = $('.article');
            $(".langButton").click(function(){
                var language = $(this).attr("data-language");
                $articles.hide();                  // Hide them all
                $("."+ language ).show(); // than show the needed ones
            });
        });
    
        function sortUsingNestedText(parent, childSelector, keySelector) {
            var items = parent.children(childSelector).sort(function(a, b) {
                var vA = $(a).find("."+keySelector).text();
                var vB = $(b).find("."+keySelector).text();
                return (vA < vB) ? -1 : (vA > vB) ? 1 : 0;
            });
            parent.append(items);
        }
    
    
        $("button.langButton").click(function() {
            sortUsingNestedText($('#sortThis'), "div",  $(this).data("language"));
        });
    

    【讨论】:

      【解决方案2】:

      您的 sortKey 数据值错误,这些值在 div 中,类为 articleethnicitygenderpetsubject。用于选择按钮的 ID 也是错误的

      $('#sblood').data("sortKey", "div.article.ethnicity");
      $('#sgroup').data("sortKey", "div.article.gender");
      $('#scanon').data("sortKey", "div.article.pet");
      $('#sability').data("sortKey", "div.article.subject");
      

      演示:Fiddle

      【讨论】:

      • 我的错!但是非常感谢!按照我的预期工作!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多