2014-12-22 103 views
0

我有一些代碼,通過SVG img元件循環並試圖換出圖像內聯SVG代碼:無法換出img元素爲SVG

(function() { 
    var el = document.querySelectorAll('img'); 
    var i; 

    for(i = 0; i < el.length; i++) { 
     var imageEl = el[i], 
      imgSrc = imageEl.src; 

     if(typeof imgSrc != 'undefined' && imgSrc.match(/\.svg$/)) { 
      var request = new XMLHttpRequest(); 
      request.open('GET', imgSrc, true); 
      request.send(); 

      request.onload = function() { 
       console.log(newImage); 
       imageEl.outerHTML = request.responseText; 
      } 
     } 
    } 

})(); 

然而,這將返回:Uncaught NoModificationAllowedError: Failed to set the 'outerHTML' property on 'Element': This element has no parent node.

我有點不確定這是爲什麼發生。我試圖從jQuery重現replaceWith函數。

回答

0

我用做異步虛假固定這一點,變化不大代碼:

(function() { 
    var el = document.querySelectorAll('img'); 
    var i; 

    for(i = 0; i < el.length; i++) { 
     var imageEl = el[i], 
      imgSrc = imageEl.src; 

     if(typeof imgSrc != 'undefined' && imgSrc.match(/\.svg$/)) { 
      var request = new XMLHttpRequest(); 

      request.onreadystatechange = function() { 
       if (request.readyState == 4 && request.status == 200) { 
        imageEl.outerHTML = request.responseText; 
       } 
      } 

      request.open('GET', imgSrc, false); 
      request.send(); 
     } 
    } 

})();