Oto rozszerzenie prototyp jQuery ($ .fn) celem jest dostarczenie nowej metody, które mogą być przykuty do funkcji jQuery().
Potrzebowałem funkcjonalności, w której potrzebowałem dodać element między listą, którą podzielę. Zostało to dodane jako parametr opcjonalny.
Przykładem jest dostępny http://jsfiddle.net/roeburg/5F2hW/
Zastosowanie funkcji jest tak:
$("ul").customSplitList(5);
funkcja jest określona w następujący sposób:
// Function definition
(function ($) {
// Function is defined here ...
$.fn.customSplitList = function (indexToSplit, elementToAddInBetween) {
// Holds a reference to the element(list)
var that = this;
var subList, newList, listLength;
// Only continue if the element is a derivitive of a list
if ($(that) && ($(that).is("ul") || $(that).is("ol"))) {
// Additionally check if the length & the split index is valid
listLength = $(that).children().length;
if ($.isNumeric(indexToSplit) && indexToSplit > 0 && indexToSplit < listLength) {
// Based on list type, create a new empty list
newList = $($(that).clone(true)).empty();
while ((subList = this.find('li:gt(' + (indexToSplit - 1) + ')').remove()).length) {
newList.append(subList);
}
if (elementToAddInBetween && $(elementToAddInBetween)) {
that.after(newList);
newList.before(elementToAddInBetween);
} else {
that.after(newList);
}
}
}
};
})(jQuery);
nadzieja pomaga.
Jest biblioteka, która to robi - https://github.com/yairEO/listBreaker – vsync