2010-10-14 23 views
5

Utilizando el siguiente código, obtengo un error INDEX_SIZE_ERR: DOM Exception 1 en la línea thisRange.setStart. El código debe atravesar una página completa, buscar instancias de searchString y luego agregar un enlace al frente de esa cadena de búsqueda. Por ejemplo, si encuentra 5 instancias de la cadena, ahora agregará el enlace delante del primero pero luego el error en el segundo y se detendrá, dejando cuatro palabras sin el enlace. ¿Algunas ideas?Javascript INDEX_SIZE_ERR: DOM Exception 1 Error para los rangos

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(); 
     } 
    } 
} 

Respuesta

5

vez que haya añadido un enlace, el documento ha cambiado. La próxima vez que llame al thisRange.setStart, está usando el índice de la cadena original, pero configurándolo en el documento ahora modificado.

Debe agregarlos en orden inverso. Intente almacenar los índices de coincidencia en una matriz, y luego recorra su matriz de índices hacia atrás para inyectar sus enlaces.

+0

Correcto ........ –

+0

De alguna manera pensé que esto podría ser lo que estaba sucediendo y pensé en el orden inverso. No sabía cómo hacer eso, sin embargo, como los bucles es un bucle while usando el objeto RegExp. ¿Alguna sugerencia? – joshholat

+0

Puede almacenar los índices de sus coincidencias en una matriz y recorrer la matriz en un bucle separado. He actualizado mi respuesta. – gilly3

0

Lo descubrí. Así es como:

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); 
} 

En lugar de añadir a la gama en el ciclo anterior, he añadido a y matriz y luego pasé por esa matriz hacia atrás.

Cuestiones relacionadas