[英]Why does the content return the same object on JavaScript?
在下面的 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';
}
我想在每個相關的搜索結果項目上搜索一個關鍵字,如果有,從結果中隱藏該項目。 然而,上面的輸出似乎重復了包含關鍵字的搜索結果,即使在我的測試樣本中,關鍵字只包含在一個項目中。
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)
所以循環正在運行,但似乎r.singleNodeValue
總是返回相同的對象。
我想知道為什么它不顯示每個項目的結果。
來自Document.evaluate MDN 文檔:
document.evaluate(".//h2", document.body, null, XPathResult.ANY_TYPE, null);
注意上面的
document.body
已被用作上下文而不是document
因此 XPath 從 body 元素開始。 (在這個例子中,"."
很重要,它表明查詢應該從上下文節點document.body
。如果"."
被省略(離開//h2
),查詢將從根節點開始( html),這會更浪費。)
所以我認為你只需要添加一個 '.' 在您的 xpath 開始時。 在這里你總是得到整個文檔中匹配的第一個元素,忽略你提供的上下文元素
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.