文档选择中的索引错误,而所选文本有一个点

wrong index in document selection, while selected text is have a dot

本文关键字:文本 有一个 选择 索引 错误 文档      更新时间:2023-09-26

我正在获取文本,它是用户从html页面中选择的。我正在数组中打印此文本的索引。

我有一段文字内容。获取所选文本的索引没有问题,而选择没有点的文本(.),

但是,当选择带句点(.)的文本时,索引值总是显示1。

例如,在下面的段中

    I am working in HTML with jquery. I want to make a webpage to highlight some text lines (line nos 15, 22, 32) in that page at a time. This can be done by left click in mouse and drag that line, so that the text line is selected with blue background.

当我选择"在html中工作"时,这在数组中看起来不错,索引打印为'5'。

但当我选择"jquery.I want"(有点)时。索引目前不可用(26)。

这是我的代码,https://jsfiddle.net/qL659gmh/7/

    <body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="test">I am working in HTML with jquery.
      I want to make a webpage to highlight some text lines (line nos 15, 22, 32) in that page at a time. This can be done by left click in mouse and drag that line, so that the text line is selected with blue background.
    I am able to get the selected lines as follows using jquery,
    </div>
    <script type="text/javascript">     
    var arr = [];
    $('#test').mouseup(function () {
        var output='';
        output += getSelectedText();
        arr.push(output);
        highlightSelected();
        $('#result').html(output);
        indx(output);
    });
    function getSelectedText() {
        if (window.getSelection) {
            return window.getSelection().toString();
        } else if (document.selection) {
            return document.selection.createRange().text;
        }
        return '';
    }
    function indx(text){
        inputText = document.getElementById("test")
        var innerHTML = inputText.innerHTML
        var index = innerHTML.indexOf(text);
        console.log("innerHTML---------------"+innerHTML)
        console.log("text---------------"+text)
        console.log("index---------------"+index)
    }       

您需要使用innerText而不是innerHtml,因为document.selection.createRange().text返回的纯文本没有任何标记,位于句点(.)之后的换行处。更清楚的是,问题不在于句点(这是jsFiddle