다음은 jQuery 자체가 객체에서 작동하도록하기위한 개념 증명 구현입니다. 객체 래퍼 (FakeNode
)을 통해, 당신은 사용에 jQuery를 속일 수 내장 된 일반 자바 스크립트 객체에 선택 엔진 (지글 지글) :
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로 요소를 포장하는 것입니다 -1]; ? –
이 장난감 예제에서는 효과가 있지만 더 깊은 나무와 큰 개체는 빠르게 분해됩니다. 예를 들어, 네트워크 패킷을 나타내는 트리를 사용하는 프로그램에서 작업하고 있는데 도달 할 수없는 패킷에 대한 ICMP 프레임을 얻기 위해 $ ('icmp [code = UNREACHABLE]', packetlist)를 작성하고 싶습니다. – brendan