使用以下代码,我在 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/