我有一些循环遍历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 :(得分:0)
我通过使用async false来修复此问题并稍微更改了代码:
(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();
}
}
})();