作为 Chrome 扩展的一部分,我在整个 DOM 中搜索每个 ID/类中包含特定单词的元素。
目前看起来像这样:
"allSelectors": document.querySelectorAll("[id*='example'][class*='example']"),
"collapse": function () {
for (var i = 0; i < MyObject.allSelectors.length; i++) {
// Manipulate MyObject.allSelectors[i] etc
}
},
首先,我想以某种方式重组它(可能使用 array
?)以便添加新的选择器很容易,就像这样:
document.querySelectorAll("[id*='example'][class*='example'][id*='other'][class*='other']")
不容易扩展或不好。
其次,我认为 document.querySelectorAll
非常慢 - 我使用它的原因是因为我需要搜索 id/class 中的任何地方(因此使用 *=
) 并且不能使用大型外部库(例如 jQuery),因为这是一个小文件并且正在被用户端注入(inject)。
是否有解决这些问题的方法?因为如果有很多比赛,那么这种缓慢可能会成为一个问题。
最佳答案
首先,我会完全选择 querySelectorAll
,我认为它没有那么慢,而且它完全适合像您这样的情况。我同意你的看法,为此添加一个库有点矫枉过正,而且它可能不像某些人认为的那样有益(让我们 test it here )。
然后,我再次同意您的观点,即当前解决方案的可扩展性不是很好,阵列才是可行之道。这是一个使用数组的非常基本的实现:
// an array of classes and ids to match
var nodes,
searches = [
'[id*="test"]',
'[class*="example"]'
];
// a simple function to return an array of nodes
// that match the content of the array
function getNodes(arr){
return Array.prototype.slice.call(document.querySelectorAll( arr.join() ));
}
nodes = getNodes(searches);
好处是可以很容易地在数组中添加或删除新的类和 ID,例如,稍后您可以添加:
searches.push('[id*="some"]');
nodes = getNodes(searches); // new nodes will be fetched
这是一个 jsbin带有完整的示例代码。
关于javascript - 重构DOM搜索方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29039036/