這裏是一個概念驗證實現獲取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