Suppose I have two containers with the same CSS applied to them and their sub items.
<div class="wrapper">
<div class="item">item</div>
<div class="dummy">distrating item</div> <!-- dummy one -->
<div class="item">item</div>
<div class="item">item</div>
...
</div>
<div class="wrapper">
<div class="item">item</div>
<div class="dummy">distrating item</div> <!-- dummy one -->
<div class="item">item</div>
<div class="item">item</div>
...
</div>
This is of course na example. but the point being is this. If I define a jQuery selector as:
$(".wrapper .item")
and then write a jQuery plugin that should do something with these items but per container, how am I suppose to get a subset of items from the whole set that belong to each container?
$.fn.extend({
randomize: function() {
if (this.length > 1)
{
var set = this;
var origSelect = set.selector;
var containers = this.parent();
$.each(containers, function() {
开发者_Go百科 var container = $(this);
var items = set.filter(?????);
....
});
}
return this;
}
});
Based on the data that I have in the inner function:
- whole set
- original element selector
- current container
Is there some jQuery selector that can help me get a subset of items from the whole set that belong to a particular item.
First possibility
This of course doesn't work:
$(origSelect, container);
which is equivalent to
$(".wrapper .item", ".wrapper");
because container CSS class is part of original selector. If it wasn't it would work. but I can't control that.
Second possibility
Filtering by
container.children();
will also fail because it will also select dummy items.
But the idea is to reuse existing jQuery set which is of course faster than selecting DOM nodes all over again which is done in both cases.
So basically I want something like:
set.filter(something);
But I don't know if there's filter for what I want.
You can compare the parent elements of each item to your current container element:
$.each(containers, function() {
var container = $(this);
var items = set.filter(function() {
return this.parentNode == container[0];
});
// ...
});
You can try this
$.fn.extend({
randomize: function() {
if (this.length > 1)
{
var set = this;
var origSelect = set.selector;
var selectorArr = origSelect.split(" ");
var itemSelector = selectorArr[selectorArr.length - 1];
var containers = this.parent();
$.each(containers, function() {
var container = $(this);
var items = container.filter(itemSelector);
....
});
}
return this;
}
});
精彩评论