问题描述
getElementsByTagName()
有两个很棒的功能:它很快而且是现场直播。但是,如果我想获得 p strong
,该怎么办?当然我可以再次使用 getElementsByTagName()
来优化选择但不会丢失新的 p
标签?
getElementsByTagName()
has 2 great features: it is fast and it is live. But what if I want to get p strong
. Of course I could refine a selection using getElementsByTagName()
again but wouldn't I lose the live effect for the new p
tags?
有没有办法将 querySelectorAll
转换为实时选择器?
Is there a way to turn querySelectorAll
into a live selector?
或者......有没有办法使用 getElementsByTagName()
和 getElementsByClassName()
创建一个以类似方式工作的函数(至少与后代一样)作为 querySelectorAll
但是生效?
Or... is there a way to use getElementsByTagName()
and getElementsByClassName()
to create a function that works in a similar way (at least with descendants) as querySelectorAll
but being live?
推荐答案
考虑使用变异观察者。使用子树:true
观察 childList
。当通知到达时,您可以使用匹配
检查每个添加的节点,以查看它是否与某个选择器匹配。
Consider using mutation observers. Watch for childList
with subtree: true
. When the notification arrives, you can examine each added node with matches
to see if it matches some selector.
function querySelectorAllLive(element, selector) {
// Initialize results with current nodes.
var result = Array.prototype.slice.call(element.querySelectorAll(selector));
// Create observer instance.
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
[].forEach.call(mutation.addedNodes, function(node) {
if (node.nodeType === Node.ELEMENT_NODE && node.matches(selector)) {
result.push(node);
}
});
});
});
// Set up observer.
observer.observe(element, { childList: true, subtree: true });
return result;
}
这篇关于是否有可能使querySelectorAll像getElementsByTagName一样生活?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!