2012-08-30 52 views
1

更新:此问题是尝试突出显示文本并将其突出显示在数据库中以便稍后加载的更大努力的一部分。如何使用Javascript获取相对Xpath

我遵循这里使用的代码:Range object with JSON 我想捕捉用户选择的文本的位置存储在数据库中,然后在ajax调用恢复。

首先,我想使我得到的是看起来的XPath这样

endXPath: "/HTML[1]/BODY[1]/DIV[1]/DIV[5]/P[3]/text()[1]" 

看起来像这样

endXPath: "/DIV[5]/P[3]/text()[1]" 

凡DIV [1]在第一个例子中具有的ID “内容。”

我相信这条道路是从这个函数

function makeXPath (node, currentPath) { 
    /* this should suffice in HTML documents for selectable nodes, XML with namespaces needs  more code */ 
    currentPath = currentPath || ''; 
    switch (node.nodeType) { 
    case 3: 
    case 4: 
     return makeXPath(node.parentNode, 'text()[' + (document.evaluate('preceding-sibling::text()', node, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength + 1) + ']'); 
    case 1: 
     return makeXPath(node.parentNode, node.nodeName + '[' + (document.evaluate('preceding-sibling::' + node.nodeName, node, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength + 1) + ']' + (currentPath ? '/' + currentPath : '')); 
    case 9: 
     return '/' + currentPath; 
    default: 
     return ''; 
    } 
} 

从我至今读我猜我需要改变contextNode来了吗?但我不知道如何完成这一任务。

回答

1

有一个JQuery插件可以完成这个调用Annotator。它内置了所有内容以突出显示,存储亮点并添加关于亮点的评论。