【问题标题】:Inner working of this jquery script这个 jquery 脚本的内部工作
【发布时间】:2011-08-28 05:10:59
【问题描述】:

我有一个依赖于这个 Script Sort.js 的 Jquery 脚本。任何机构都可以这是如何工作的

jQuery.fn.sort = (function(){

    var sort = [].sort;

    return function(comparator, getSortable) {

        getSortable = getSortable || function(){return this;};

        var placements = this.map(function(){

              var sortElement = getSortable.call(this),               
                parentNode = sortElement.parentNode,                      
                // Since the element itself will change position, we have
                // to have some way of storing it's original position in
                // the DOM. The easiest way is to have a 'flag' node:
                nextSibling = parentNode.insertBefore(
                    document.createTextNode(''),
                    sortElement.nextSibling
                );

            return function() {

                if (parentNode === this) {
                    throw new Error(
                        "You can't sort elements if any one is a descendant of another."
                    );
                }

                // Insert before flag:
                parentNode.insertBefore(this, nextSibling);
                // Remove flag:
                parentNode.removeChild(nextSibling);

            };

        });

        return sort.call(this, comparator).each(function(i){
            placements[i].call(getSortable.call(this));
        });

    };

})();

我从这个链接http://qd9.co.uk/projects/jQuery-Plugins/sort/demo.html得到这个脚本

【问题讨论】:

  • 你能缩小你的问题范围吗?它过于宽泛。你不明白哪些部分?
  • @patrick dw:很抱歉这样说。我无法理解任何代码行。除了我知道这是一个闭包

标签: jquery jquery-ui jquery-selectors


【解决方案1】:

它基本上需要三个输入:

  • this 是您调用它的 jQuery 对象,例如如果是$("#my-id").sort(),那么this 就是$("#my-id")
  • comparator 是与JavaScript's native Array.prototype.sort 接受的同类型的比较函数
  • getSortable 是一个可选的转换函数,在实际排序之前应用于已排序的 DOM 元素。它的行为仍然让我有点困惑。它似乎只有在返回另一个 DOM 元素时才有效?

通过线路获取Array.prototype.sort方法

var sort = [].sort;

然后它与comparator 函数一起使用它来获取 jQuery 对象的排序版本,这是“类似数组”的,因为它具有属性012、...和length 属性:

sort.call(this, comparator)

然后循环遍历结果,在 DOM 元素本身(默认)上调用 placements[i],或者在给定 DOM 元素时调用 getSortable 返回的任何内容:

sort.call(this, comparator).each(function(i){
        placements[i].call(getSortable.call(this));
    });

所以真正的魔法发生在placements 数组的创建中。经过一番思考,我们看到placements[i] 是一个函数,它将其输入插入到与thisith 元素相同的位置, 排序发生之前。因此,使用ith sorted 元素作为输入调用placement[i] 会导致将ith sorted 元素放置在ith“槽”中,即ith unsorted 元素所在的位置。在 placements 数组创建中使用“标志”节点的整个业务是这样的,即使您开始用新的排序元素替换它们,它也可以跟踪原始“插槽”的位置。

另外值得注意的是:它(相当不必要的 IMO)将自己包装在一个立即执行的匿名函数中,该函数本身返回一个采用 comparatorgetSortable 参数的函数。因此分配给jQuery.fn.sort 的实际结果是双参数函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多