Вот реализация концепции для того, чтобы заставить сам jQuery работать над объектами. С помощью обёртки объекта (FakeNode
) вы можете обмануть jQuery, используя встроенный механизм выбора (Sizzle) для простых объектов JavaScript:
function FakeNode(obj, name, parent) {
this.obj = obj;
this.nodeName = name;
this.nodeType = name ? 1 : 9; // element or document
this.parentNode = parent;
}
FakeNode.prototype = {
documentElement: { nodeName: "fake" },
getElementsByTagName: function (tagName) {
var nodes = [];
for (var p in this.obj) {
var node = new FakeNode(this.obj[p], p, this);
if (p === tagName) {
nodes.push(node);
}
Array.prototype.push.apply(nodes,
node.getElementsByTagName(tagName));
}
return nodes;
}
};
function $$(sel, context) {
return $(sel, new FakeNode(context));
}
И использование будет:
var obj = {
foo: 1,
bar: 2,
child: {
baz: [ 3, 4, 5 ],
bar: {
bar: 3
}
}
};
function test(selector) {
document.write("Selector: " + selector + "<br>");
$$(selector, obj).each(function () {
document.write("- Found: " + this.obj + "<br>");
});
}
test("child baz");
test("bar");
Предоставление вывода:
Selector: child baz
- Found: 3,4,5
Selector: bar
- Found: 2
- Found: [object Object]
- Found: 3
Конечно, вам придется реализовать намного больше, чем выше, чтобы поддерживать более сложные селекторы.
Кстати, вы видели jLinq ?