Javascript INDEX_SIZE_ERR : DOM Exception 1 Error for ranges

标签 javascript dom range

使用以下代码,我在 thisRange.setStart 行收到 INDEX_SIZE_ERR: DOM Exception 1 错误。该代码旨在遍历整个页面,找到 searchString 的实例,然后在该搜索字符串前面添加一个链接。例如,如果它找到字符串的 5 个实例,现在它将在第一个前面添加链接,但随后在第二个上出错并停止,留下四个没有链接的单词。有什么想法吗?

    if(searchString.length > 0) { // make sure the string isn't empty, or it'll crash.
    // Search all text nodes
    for(var i = 0; i < textNodes.length; i++) {
        // Create a regular expression object to do the searching
        var reSearch = new RegExp(searchString,'gmi'); // Set it to 'g' - global (finds all instances), 'm' - multiline (searches more than one line), 'i' - case insensitive
        var stringToSearch = textNodes[i].textContent;

        while(reSearch(stringToSearch)) { // While there are occurrences of the searchString
            // Add the new selection range
            var thisRange = document.createRange();

            //alert((reSearch.lastIndex - searchString.length) + " <-> " + reSearch.lastIndex);

            thisRange.setStart(textNodes[i], reSearch.lastIndex - searchString.length); // Start node and index of the selection range
            thisRange.setEnd(textNodes[i], reSearch.lastIndex); //  End node and index of the selection

            var myLink = document.createElement('a'); 
            var href = document.createAttribute('href'); 
            myLink.setAttribute('href','http://www.google.com'); 
            myLink.innerText ="GO";
            thisRange.insertNode(myLink);

            //theSelection.addRange(thisRange); // Add the node to the document's current selection
            //thisRange.deleteContents();
        }
    }
}

最佳答案

添加链接后,文档就发生了变化。当您下次调用 thisRange.setStart 时,它使用原始字符串中的索引,但将其设置在现在已更改的文档中。

您需要以相反的顺序添加它们。尝试将匹配索引存储在数组中,然后向后遍历索引数组以注入(inject)链接。

关于Javascript INDEX_SIZE_ERR : DOM Exception 1 Error for ranges,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3937678/

相关文章:

html - 获取具有绝对位置的父元素的子元素的宽度

c# - 为一组随机值生成多个范围

excel - 如何在excel VBA中为具有命名范围的图表设置源数据

ruby-on-rails - 如何查找两个范围内的共同日期

javascript - 需要电子邮件验证建议

javascript - jQuery $ .ajax-从成功函数调用错误函数?

javascript - Appcelerator 钛/合金型号 : How do I modify this sorting method to sort a string that contains numbers

Javascript 输入字段值未定义

javascript - 为什么绑定(bind)参数不指向实际的函数参数

javascript - 子节点多个javascript XML