我用這個小插件封裝:jQuery的包裝忽略隱藏的div
https://github.com/tsevdos/nwrapper
(function($) {
$.fn.nwrapper = function(options){
var defaults = {
wrapEvery : 1,
defaultClasses : true,
extraClasses : false,
htmlStructure : 'div'
};
settings = $.extend({}, defaults, options);
var elements = $(this).children();
var elementsLen = elements.length;
for (var i = 0, numb = 1; i < elementsLen; i += settings.wrapEvery, numb++){
// Default Classes Array
var classes = [];
if (settings.defaultClasses) {
classes[0] = 'wrapper';
classes[1] = 'wrapper-' + numb;
if (numb==1) {
classes[2] = 'first';
}
if (numb==Math.ceil(elementsLen/settings.wrapEvery)) {
classes[2] = 'last';
}
}
// Merge Default class with Extra Class
if (settings.extraClasses) {
$.merge(classes, settings.extraClasses);
}
// If you find any classes crete the class string
if (classes.length > 0) {
htmlClassesString = 'class="' + classes.join(" ") + '"';
} else {
htmlClassesString = '';
}
elements.filter(':eq(' + i + '), :lt(' + (i + settings.wrapEvery) + '):gt(' + i + ')').wrapAll('<' + settings.htmlStructure + ' ' + htmlClassesString + ' />');
}
return $(this);
};
})(jQuery);
基本佈局是:
<div id="container">
<div class="filter1">Value</div>
<div class="filter2">Value</div>
<div class="filter3">Value</div>
<div class="filter1">Value</div>
<div class="filter2">Value</div>
<div class="filter3">Value</div>
<div class="filter1">Value</div>
<div class="filter2">Value</div>
<div class="filter3">Value</div>
...
</div>
初始化插件:
$('#container').nwrapper({ wrapEvery : 3 });
我使用select過濾器隱藏/顯示子div,然後重新初始化插件。我想知道是否可以從包裝計數中排除隱藏的div?
最後,我使用jquery循環來顯示包裝的div,所以隱藏的div應該在內部包裝(但不包括在內)。否則,循環會將每個隱藏的div視爲一個項目。
也許這個插件不是我想要實現的最佳工具。它會產生以下內容:
<div id="container">
<div class="wrapper wrapper-1 first">
<div class="filter1">Value</div>
<div class="filter2">Value</div>
<div class="filter3" style="display:none;">Value</div>
</div>
<div class="wrapper wrapper-2">
<div class="filter1">Value</div>
<div class="filter2">Value</div>
<div class="filter3" style="display:none;">Value</div>
</div>
<div class="wrapper wrapper-3 last">
<div class="filter1">Value</div>
<div class="filter2">Value</div>
<div class="filter3" style="display:none;">Value</div>
</div>
</div>
我想包裝每三個可見的div,但也包括隱藏的。
<div id="container">
<div class="wrapper wrapper-1 first">
<div class="filter1">Value</div>
<div class="filter2">Value</div>
<div class="filter3" style="display:none;">Value</div>
<div class="filter1">Value</div>
</div>
<div class="wrapper wrapper-2 last">
<div class="filter2">Value</div>
<div class="filter3" style="display:none;">Value</div>
<div class="filter1">Value</div>
<div class="filter2">Value</div>
<div class="filter3" style="display:none;">Value</div>
</div>
</div>
是的。這工作。問題是我使用jquery循環來顯示包裝的div。我需要將隱藏的div包含在包裝div中(但不包括在內)。否則循環會將每個隱藏的div包括爲一個項目。 – teeraina
@teeraina,我已經更新了我的答案看看。 –
感謝您的幫助!不幸的是,它仍然留下隱藏的divs,並在包裝div後列出它們。 – teeraina