使用以下代碼,我在thisRange.setStart行上得到INDEX_SIZE_ERR:DOM Exception 1錯誤。該代碼旨在遍歷整個頁面,查找searchString的實例,然後在該搜索字符串前添加一個鏈接。例如,如果它找到了5個字符串的實例,現在它會將鏈接添加到第一個字符串的前面,然後在第二個字符串上出現錯誤並停止,並留下四個沒有鏈接的單詞。有任何想法嗎?Javascript INDEX_SIZE_ERR:DOM Exception 1範圍的錯誤
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();
}
}
}
正確........ – 2010-10-14 22:57:41
我有點認爲這可能是發生了什麼事情,並想到相反的順序。不過,我不知道該怎麼做,因爲循環是使用RegExp對象的while循環。有什麼建議麼? – joshholat 2010-10-15 04:55:37
您可以將匹配的索引存儲在數組中,然後在單獨的循環中遍歷數組。我已經更新了我的答案。 – gilly3 2010-10-15 19:18:21