內的所有鏈接:Greasemonkey的,XPath的:找到考慮到錶行
<tr>
<td><a href="http://foo.com">Keyword 1</a></td>
<td><a href="http://bar.com">Keyword 2</a></td>
<td><a href="http://wombat.com">Keyword 3</a></td>
</tr>
<tr>
<td><a href="http://blah.com">Keyword 4</a></td>
<td><a href="http://woof.com">Keyword 5</a></td>
<td><a href="http://miaow.com">Keyword 6</a></td>
</tr>
我需要在表格單元格內的相互匹配URI。整個文檔中的關鍵字是一致的。然而
var links_in_document = document.evaluate(
"//a[starts-with(text(),'Keyword')]",
document,
null,
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
null);
,即使我有一個簡單的方法來引用TR節點,我似乎無法找到正確的XPath以獲得鏈接:我可以匹配整個文檔的鏈接,沒有麻煩行。下面的代碼片段似乎給了我第一次TD上的第一個鏈接,但不是其餘。幫幫我?
var links_in_row = document.evaluate(
".//a[starts-with(text(),'Keyword')]",
row,
null,
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
null);
(其中「行」是上下文節點)。
編輯:也許我不清楚,我可以找到文檔級別的鏈接就好了。我試圖通過使用TR節點作爲XPath的上下文來隔離單行中的鏈接。
編輯:解決方案,感興趣。我正在處理的破解標記沒有id屬性,所以我添加了一些並能夠繼續。摘錄:
var exhibit_link;
for(var i = 0; i < all_exhibit_links.snapshotLength; i++) {
exhibit_link = all_exhibit_links.snapshotItem(i);
// The rows have no unique ID, so we need to give them one.
// This will give the XPath something to 'latch onto'.
exhibit_link.parentNode.parentNode.id = 'ex_link_row_' + i.toString();
exhibit_link.addEventListener("click",
function(event) {
var row_id = event.target.parentNode.parentNode.id;
// Find only those links that are within rows with the corresponding id
var row_links = document.evaluate(
"id('" + row_id + "')/td/a[starts-with(text(),'Exhibit')]",
document,
null,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
null);
// Open each link in a new tab
for(var j = 0; j < row_links.snapshotLength; j++) {
row_link = row_links.snapshotItem(j);
GM_openInTab(row_link.href);
}
// Suppress the original function of the link
event.stopPropagation();
event.preventDefault();
},
true);
}
我用相同的代碼得到了相同的結果,或多或少。一定是在這裏複製粘貼之外的東西。 – anschauung 2009-07-03 10:08:41