简体   繁体   English

为什么内容在 JavaScript 上返回相同的对象?

[英]Why does the content return the same object on JavaScript?

In Javascript code below, which is running on the Chrome console (the web page is just a random search result on Google):在下面的 Javascript 代码中,它在 Chrome 控制台上运行(网页只是在 Google 上的随机搜索结果):

var result = document.getElementsByClassName('g')

var xpath = "//h3[contains(text(),'wrong')]";

for (let i = 0; i < result.length; i++) {
    var r = document.evaluate(xpath, result[i], null, XPathResult.FIRST_ORDERED_NODE_TYPE, null)
    console.log(i);
    console.log(r.singleNodeValue);
    result[i].style.display = 'none';
}

I want to search for a keyword on each relevant search result item, and if there is, hide the item from the result.我想在每个相关的搜索结果项目上搜索一个关键字,如果有,从结果中隐藏该项目。 However, the output above seems to repeat the search result that has the keyword, even though in my test sample the keyword is included only on one item.然而,上面的输出似乎重复了包含关键字的搜索结果,即使在我的测试样本中,关键字只包含在一个项目中。

0
<h3 class=​"LC30li DRV0Md">​Why is this code not working</h3>​
1
<h3 class=​"LC30li DRV0Md">Why is this code not working</h3>​

..... (up to the last search item)

So the loop is running but it seems that r.singleNodeValue always returns the same object.所以循环正在运行,但似乎r.singleNodeValue总是返回相同的对象。

I wonder why it doesn't show a result from each item.我想知道为什么它不显示每个项目的结果。

From Document.evaluate MDN docs:来自Document.evaluate MDN 文档:

document.evaluate(".//h2", document.body, null, XPathResult.ANY_TYPE, null);

Notice in the above document.body has been used as the context instead of document so the XPath starts from the body element.注意上面的document.body已被用作上下文而不是document因此 XPath 从 body 元素开始。 (In this example, the "." is important to indicate that the querying should start from the context node, document.body . If the "." was left out (leaving //h2 ) the query would start from the root node (html) which would be more wasteful.) (在这个例子中, "."很重要,它表明查询应该从上下文节点document.body 。如果"."被省略(离开//h2 ),查询将从根节点开始( html),这会更浪费。)

So I think you just need to add a '.'所以我认为你只需要添加一个 '.' at the start of your xpath.在您的 xpath 开始时。 Here you always get the first element matching in the whole document, ignoring the context element you provided在这里你总是得到整个文档中匹配的第一个元素,忽略你提供的上下文元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM