簡體   English   中英

如何控制jQuery插件使用.each()進行迭代的順序?

[英]How can I control the order my jQuery plugin iterates with .each()?

我創建了一個插件,該插件可克隆元素以進行快速原型制作。 插件將迭代每個在元素上具有“ data-clone”數據屬性的元素,並在屬性中設置克隆數量。

例:

<table data-clone="3">
    <thead>
        <tr>
            <th>#</th>
            <th>Name</th>
            <th>Project</th>
        </tr>
    </thead>
    <tbody>
        <tr data-clone="4">
            <td>1</td>
            <td>Steve Sax</td>
            <td>Something here.</td>
        </tr>
    </tbody>
</table>

這似乎在第一個元素上效果很好。 但是,如果我有一個嵌套項目,容器在其中被克隆,里面的元素也是如此。 似乎它會克隆嵌套的項目,並且首先克隆外部的項目,但不會將那些嵌套的項目克隆到新克隆的外部容器中。

我在這里有一個小提琴: 小提琴

它具有插件和調用。 如果單擊“運行”,您應該完全明白我的意思。

但是,我覺得如果.each()方法首先從嵌套項中進行迭代,然后逐步進行,則所有克隆都是正確的。

提前致謝,

亞當。

這是插件本身供參考。 同樣,所有人都在擺弄。

/*! Adamin Clone - v0.1.0 - 2012-09-29
  * https://github.com/pensive612/Adamin-Clone
  * Copyright (c) 2012 Adam L.; Licensed MIT, GPL */

(function(window, document, $, undefined) {
    var Project = function(elem, options) {
      this.elem = elem;
      this.$elem = $(elem);
      this.options = options;
      this.metadata = this.$elem.data('clone-cap');
};

Project.prototype = {
  defaults: {
    cloneCap: 100
  },
  init: function() {
    this.config = $.extend({}, this.defaults, this.options, this.metadata);

    this.getCloneValue(this.$elem);

    return this;
  },
  getCloneValue: function(elem) {
    var configCap = this.config.cloneCap;
    var cloneValue = elem.data('clone');

    // parse data-clone value
    cloneValue = this.parseCloneValue(cloneValue);

    // if data-clone value is valid, send to clone function
    if ( cloneValue && (cloneValue < configCap) ) {
      this.cloneItem(this.$elem, cloneValue);

    // otherwise, return false
    } else {

      if (cloneValue > configCap) {
        window.console.log('Your data-clone value is too high for the defaults.  Please check documentation to override cap in config.');
      }

      return false;
    }
  },
  parseCloneValue: function(value) {
    var cloneValue = parseInt(value, 10);
    return cloneValue;
  },
  cloneItem: function(elem, value) {
    var elemClone;

    for (var i = value; i > 0; i--) {
      elemClone = elem.clone(true);
      elemClone.removeAttr('data-clone');
      elemClone.addClass('clone-' + i);
      elemClone.insertAfter(elem);
    }
  }
};

Project.defaults = Project.prototype.defaults;

$.fn.adaminClone = function(options, callback) {

  if (typeof callback === 'function') {
    callback.call(this);
  }

  return this.each(function() {
    new Project(this, options).init();
  });
};

window.Project = Project;

}(window, document, jQuery));

好的,我為您准備了一些東西。

檢查這個簡化的小提琴

基本上,您從最深的元素開始克隆並向上克隆。 注釋在代碼中。

var elements = $.find('[data-clone]'); //get all the elements that need to be cloned
var elementsData = []; //will store and sort the elements

//store the elements with their depth
$.each(elements, function(i, element) {

    var obj = {};
    obj.element = $(element);
    obj.depth = $(element).parents().length;

    elementsData.push(obj);

    // This can be optimized, it's just easier to understand the code.
    // Alternatively use 
    // elementsData.push({ element : $(element), depth : $(element).parents().length }); 
})

//sort them by deepest element
elementsData.sort(SortByDepth);


$.each(elementsData, function(i, elementData) {
    var element = elementData.element;

    //clone ot the number of times wanted.
    for (var c = 0; c < element.attr('data-clone'); c++) {
        element
            .clone(true)
            .removeAttr('data-clone')
            .addClass('clone-' + c).
            insertAfter(element);
    }
})

//function that sorts the elements;
function SortByDepth(a, b){
  var aDepth = a.depth;
  var bDepth = b.depth;
  return ((aDepth > bDepth) ? -1 : ((aDepth < bDepth) ? 1 : 0));
}

注意:在data-clone = 4中,腳本會將其克隆4次,因此屏幕上總共有5個(因為已經存在5個)。 您想要4,在for循環中插入

for (var c = 0; c < parseInt(element.attr('data-clone') - 1); c++) {

ComputerArts在重寫功能方面做得非常出色。 但是,我僅通過修改就能夠維護插件模式和可擴展性:

return this.each(function() {
  new Project(this, options).init();
});

對此:

  return this.sort(function(a, b) {
    var va = $(a).parents('[data-clone]').length;
    var vb = $(b).parents('[data-clone]').length;
    return vb - va;
  }).each(function() {
      new Project(this, options).init();
  });

使用parent()。length是衡量深度的好方法。 感謝ComputerArts和Shoky將我帶到需要的地方。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM