这里是一个概念验证实现获取jQuery本身的工作对象。通过对象包装(FakeNode
),你可以欺骗的jQuery到使用其内置的纯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?
使用jQuery包裹的元素,然后循环正是在那里,你不喜欢obj.child.baz理由[obj.child.baz.length -1]; ? – 2009-07-17 16:40:46
对于这个玩具的例子来说,它可以工作,但是对于更深的树木和更大的物体很快就会崩溃。例如,我正在研究一个使用树代表网络数据包的程序,并且我希望能够编写$('icmp [code = UNREACHABLE]'数据包列表)来获取ICMP帧以供不可达数据包使用。 – brendan 2009-07-17 16:46:10