Javascript 从Xpath获取文本并突出显示它

Javascript 从Xpath获取文本并突出显示它,javascript,xpath,Javascript,Xpath,我正在尝试建立一个电子酒吧阅读器。我能够突出显示用户选择的文本,并获得该特定选定文本的x路径。之后,我尝试构建一个函数,该函数以x路径为参数,通过改变背景颜色来显示用户选择的文本。但它不起作用 代码:- function uiWebview_restoreSelection() { var selectionDetails = "/HTML[1]/BODY[1]/DIV[1]/text()[1]|910|/HTML[1]/BODY[1]/DIV[1]/text()[1]|930"; //aler

我正在尝试建立一个电子酒吧阅读器。我能够突出显示用户选择的文本,并获得该特定选定文本的x路径。之后,我尝试构建一个函数,该函数以x路径为参数,通过改变背景颜色来显示用户选择的文本。但它不起作用

代码:-

function uiWebview_restoreSelection() {
var selectionDetails = "/HTML[1]/BODY[1]/DIV[1]/text()[1]|910|/HTML[1]/BODY[1]/DIV[1]/text()[1]|930";
//alert("selectionDetails"+selectionDetails);
if (selectionDetails != null) {
    selectionDetails = selectionDetails.split(/\|/g);
    alert("selectionDetails" + selectionDetails);
    if (typeof window.getSelection != 'undefined') {
        var selection = window.getSelection();
        selection.removeAllRanges();
        var range = document.createRange();
        var selectionDetails0 = selectionDetails[0];
        alert("selectionDetails0" + selectionDetails0);
        selectionDetails0 = selectionDetails0.replace(/\//g, "/h:");
        selectionDetails0 = selectionDetails0.replace("h:t", "t");
        alert("selectionDetails0" + selectionDetails0);
        var selectionDetails2 = selectionDetails[2];
        alert("selectionDetails2" + selectionDetails2);
        selectionDetails2 = selectionDetails2.replace(/\//g, "/h:");
        selectionDetails2 = selectionDetails2.replace("h:t", "t");
        alert("selectionDetails2" + selectionDetails2);
        range.setStart(document.evaluate(selectionDetails0, document, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue, Number(selectionDetails[1]));
        range.setEnd(document.evaluate(selectionDetails2, document, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue, Number(selectionDetails[3]));
        document.designMode = "on";
        var newSpanMark = document.createElement("span");
        document.execCommand("HiliteColor", false, "red");
        range.insertNode(newSpanMark);
        document.designMode = "off";

    }
}
}
请针对以上问题提出建议


提前感谢

这段代码看起来很复杂-你能展示一个你正在解析的xml的例子吗?/HTML[1]/BODY[1]/DIV[1]/text()[1]| 910 |/HTML[1]/BODY[1]/DIV[1]/text()[1]| 930-这是用户选择文本的x路径开始节点和结束节点。我不是在解析xml。我有一个函数,它可以获取用户选择的文本的x路径。因此,我的理解是:在这种情况下,您想突出显示XPath表达式给出的文本节点的字符910到930吗?你能告诉我们你的代码现在到底在做什么吗,这就是它产生的不正确结果吗?是的。它应该突出显示xpath表达式给出的910到930之间的文本。我试图将xpath放在特定的可跟踪格式中。但它跟踪xpath的第一个文本节点。您可以编写一个新函数来跟踪xpath从第一个节点到最后一个节点的文本并突出显示文本吗?您可以用JavaScript编写一个函数,将xpath作为参数(比如:-/HTML[1]/BODY[1]/DIV[1]/text([1]| 910 |/HTML[1]/BODY[1]/DIV[1]/text()[1]| 930)并返回与该xpath相关的相应文本吗?