我正在执行大量 document.evaluate,然后使用 result.snapshotLength
上的 for 循环遍历每个结果。
因为我在每个循环(thisDiv.parentNode.removeChild
)中做同样的事情,所以我只想做一个循环。
我读过:
The fifth parameter can be used to merge the results of two XPath queries. Pass in the result of a previous call to document.evaluate, and it will return the combined results of both queries
所以我尝试了:
comDivs = document.evaluate(
"//div[@class='class name 1']",
document,
null,
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
null);
ggDivs = document.evaluate(
"//div[@class='class name 2']",
document,
null,
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
comDivs);
但这不行(虽然我没有错误日志,但就是不行)。
这样做的正确方法是什么?我可以运行不同的 XPath 查询并合并结果吗?或者有没有办法将正则表达式或某种替代方法传递给查询本身?
我现在的代码是:http://userscripts.org/scripts/review/58939
感谢您的帮助!
最佳答案
您可以在用户脚本中简化您的 XPath 并使用“|
”连接单个表达式:
"//div[@class='reactionsCom reactionsNiv1 first'] | " +
"//div[@class='googleBanner'] | " +
"//div[@class='blocE1B-16b'] | " +
"//div[@class='blocE1B-16b clear']"
或者在一个条件严苛的表达式中更好:
"//div[@class='reactionsCom reactionsNiv1 first' or " +
"@class='googleBanner' or " +
"@class='blocE1B-16b' or " +
"@class='blocE1B-16b clear']"
对于上面的示例,如果第一个查询的结果包含它们,则第二个查询只会找到匹配项,即如果 //div[@class='class name 2']
其中第一个查询的结果节点的子节点 //div[@class='class name 2']
。
关于javascript - 从 document.evaluate 合并 XPathResults,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1502739/