简体   繁体   English

默认使用jQuery排序列表

[英]Sorted list by default using jQuery

I leveraged the jQuery code at http://jsfiddle.net/daveSalomon/bcbxftr6/1/ and created the following code: 我利用http://jsfiddle.net/daveSalomon/bcbxftr6/1/上的jQuery代码创建了以下代码:

HTML: HTML:

<div class="featuredcomments left"><span class="featuredon">[Unchecked icon] To Top</span><span class="featuredoff">[Checked icon] Original</span></div>
<ol>
  <li>Coffee</li>
  <li>Juice</li>
  <li class="featured">Tea</li>
  <li class="featured">Milk</li>
  <li>Apple</li>
</ol>

jQuery: jQuery的:

$(document).ready(function () {
        $('.featuredon').show();
        $('.featuredoff').hide();

$('.featuredcomments').click(function(){
    var $ul = $(this).next('ol');
    if(!$ul.data('sorted')){
        $ul.data('original', $ul.html());
        $ul.data('sorted', true);
        $ul.prepend($ul.find('li.featured'));
        $('.featuredon').hide();
        $('.featuredoff').show();

    } else {
        $ul.data('sorted', false);
        $ul.html($ul.data('original'));
            $('.featuredon').show();
        $('.featuredoff').hide();

    }
});
});

Demo 演示版

By default, the page shows the original list, but I want to make the sorted list (that is, the list with the "featured" items on top.) I tried to make further changes to make it done, but I couldn't. 默认情况下,该页面显示原始列表,但是我想创建排序列表(即,列表顶部带有“功能”项的列表。)我试图进行进一步的更改以使其完成,但是我无法。

How can this be modified to show the "sorted" list by default? 默认情况下如何修改它以显示“排序”列表?

Thank you very much. 非常感谢你。

Place the code of click event in a new funtion sort and call it with show() and hide() : 将click事件的代码放入新的函数排序中 ,并使用show()hide()进行调用:

$(document).ready(function () {
    sort = function(_this){
        var $ul = $(_this).next('ol');
        if(!$ul.data('sorted')){
            $ul.data('original', $ul.html());
            $ul.data('sorted', true);
            $ul.prepend($ul.find('li.featured'));
            $('.featuredon').hide();
            $('.featuredoff').show();

        } else {
            $ul.data('sorted', false);
            $ul.html($ul.data('original'));
                $('.featuredon').show();
            $('.featuredoff').hide();            
        }
    }

    $('.featuredon').show();
    $('.featuredoff').hide();
    sort($('.featuredcomments'));

    $('.featuredcomments').click(function(){
        sort($(this));
    });
});

Find your Fiddle Updated Here . 找到您的小提琴在这里更新。

Answer is identical to same question you asked here using change event...trigger the event once the handler is created 答案与您使用更改事件在此处询问的问题相同...一旦创建处理程序,便触发事件

$('.featuredcomments').click(function(){
    // your event handling code
    ...

  /* now trigger the event */
}).click();

DEMO 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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