[英]Javascript INDEX_SIZE_ERR: DOM Exception 1 Error for ranges
使用以下代码,我在thisRange.setStart行上得到INDEX_SIZE_ERR:DOM异常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
,它将使用原始字符串中的索引,但会在现在更改的文档中进行设置。
您需要以相反的顺序添加它们。 尝试将匹配索引存储在数组中,然后向后移动索引数组以注入链接。
我想到了。 这是如何做:
for (var i = rangeArray.length - 1; i >= 0; i--) {
var myLink = document.createElement('a');
var href = document.createAttribute('href');
myLink.setAttribute('href','http://www.google.com');
myLink.innerText ="GO";
rangeArray[i].insertNode(myLink);
}
我没有将其添加到上述循环中的范围,而是将其添加到and数组,然后向后遍历该数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.