IE7:如何创建真正的 NodeList?
我正在尝试使我当前的项目兼容 IE7。我们没有使用 jQuery,而是使用 querySelectorAll
来满足我们的选择器需求。但是,IE7 不支持 querySelectorAll
,因此我使用 中的代码对其进行了猴子修补https://gist.github.com/868532。它实际上工作得很好,除了一个小区别:它返回一个数组,而不是像原始 querySelectorAll
那样的 NodeList
。由于我希望尽可能保持兼容性,因此我想让该函数返回一个 NodeList
。使用在网上找到的一些方法,我已经调整了要点:
(function(d) {
d=document, a = d.styleSheets[0] || d.createStyleSheet();
if (! vxJS.isHostMethod(d, 'querySelectorAll')) {
d.querySelectorAll = function(e) {
a.addRule(e,'f:b');
for (var l=d.all, b=0, c=d.createDocumentFragment(),f=l.length; b<f; b++) {
l[b] && l[b].currentStyle.f && c.appendChild(l[b].cloneNode(true));
}
a.removeRule(a.rules.length - 1);
return c.childNodes;
};
}
})();
我的代码问题是 appendChild
从 DOM 树中的原始位置删除了一个节点,因此我尝试使用以下命令创建一个克隆: cloneNode
,这显然会创建有效的节点克隆,它们不是原始节点,因此不能在进一步的代码中使用。
有什么方法可以将真实的节点引用放入 NodeList 中吗?
I'm trying to make my current project IE7-compatible. We are not using jQuery, but instead using querySelectorAll
for our selector needs. However, IE7 doesn't support querySelectorAll
, so I've monkey-patched it with code from https://gist.github.com/868532. It actually works fine, except for one small difference: instead of a NodeList
like the original querySelectorAll
, it returns an array. Since I'd like to stay as compatible as possible, I wanted to make that function return a NodeList
. Using some method found on the net, I've adapted the gist to this:
(function(d) {
d=document, a = d.styleSheets[0] || d.createStyleSheet();
if (! vxJS.isHostMethod(d, 'querySelectorAll')) {
d.querySelectorAll = function(e) {
a.addRule(e,'f:b');
for (var l=d.all, b=0, c=d.createDocumentFragment(),f=l.length; b<f; b++) {
l[b] && l[b].currentStyle.f && c.appendChild(l[b].cloneNode(true));
}
a.removeRule(a.rules.length - 1);
return c.childNodes;
};
}
})();
My problem with this code is that appendChild
removes a node from its original location in DOM tree, therefore I tried creating a clone with cloneNode
, which obviously creates valid node clones, which are not the original nodes and thus cannot be used in further code.
Is there any way I can put a real node reference into a NodeList?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这是不可能的。
IE7 能够生成的 NodeList 实例是实时 NodeList。但是,
querySelectorAll
方法被定义为返回静态 NodeList 实例。我不相信 IE7 知道静态 NodeList 是什么 - 这些(据我所知)仅在 Selectors API 中引入。在此处了解实时 NodeList 和静态 NodeList .
I don't think that it can be done.
The NodeList instances which IE7 is able to produce are live NodeLists. However, the
querySelectorAll
method is defined to return a static NodeList instance. I don't believe that IE7 knows what a static NodeList is - those were (afaik) only introduced in the Selectors API.Read about live NodeLists and static NodeLists here.
也许你可以通过添加 item() 方法使你的数组模仿 NodeList。
Perhaps you can make your Array mimicking NodeList by adding the item() method.