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

标签 javascript jquery html

我正在获取用户从 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。我想要”(有点)时。索引不可用(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

关于javascript - 文档选择中的索引错误,而所选文本有一个点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34647985/

相关文章:

jquery - 如何在窗口滚动的特定高度触发引导模式,仅一次?

javascript - 如何在jquery中用CDATA标签包装一些html?

html - 当用户在固定位置 div 上滚动时防止正文滚动

javascript - 通过 DOM 将文本添加到 JavaScript 中的现有文本元素

Javascript 用 where 条件比较 2 个对象数组

jquery - 用 jquery 去除所有 html 标签?

html - &lt;input type=number> 并在 Chrome 中使用小数点后一位的格式

javascript - Angular JS 识别摘要完成事件并在 View 更改期间从 angular js 中的 url 中删除#

javascript - 使用 jQuery 显示加载指示器

javascript - jQuery 在 remove() 之后取消选中复选框;