鉴于:
<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 );
}