犯罪嫌疑人X
使用img带有srcin 的标签实际上会为您向服务器发出 HTTP 请求。在这种情况下,您必须自己提出请求。您可以使用 JavaScript 原生的 which 来做到这一点Fetch API。// This should be the path to your SVG file.// Modify if incorrect.const svgFilePath = 'public/images/my_image.svg';// Select the current image.const image = document.querySelector('.svg');// Create a new dom parser to turn the SVG string into an element.const parser = new DOMParser();// Fetch the file from the server.fetch(svgFilePath) .then(response => response.text()) .then(text => { // Turn the raw text into a document with the svg element in it. const parsed = parser.parseFromString(text, 'text/html'); // Select the <svg> element from that document. const svg = parsed.querySelector('svg'); // If both the image and svg are found, replace the image with the svg. if (image !== null && svg !== null) { image.replaceWith(svg); } });并处理多个文件。在本例中,我使用了一个包含对象的数组,这些对象保存id要获取的图像元素的 和srcsvg 文件的 。// Array of object containing the id of the image you want to replace// and the src of the SVG that takes it's place.const svgFiles = [ { id: 'image1', src: 'public/images/my_image_1.svg' }, { id: 'image2', src: 'public/images/my_image_2.svg' }, { id: 'image3', src: 'public/images/my_image_3.svg' },];// Create a new dom parser to turn the SVG string into an element.const parser = new DOMParser();// Loop over each object in the array and use the id and src// with a destructuring assignment.for (const { id, src } of svgFiles) { // Find the image. If it is not there, continue with the // loop to the next iteration. let image = document.getElementById(id); if (image === null) continue; // Fetch the file from the server. fetch(src) .then(response => response.text()) .then(text => { // Turn the raw text into a document with the svg element in it. const parsed = parser.parseFromString(text, 'text/html'); // Select the <svg> element from that document. const svg = parsed.querySelector('svg'); // If the svg is found, replace the image with the svg. // Otherwise, continue the loop. if (svg === null) continue; image.replaceWith(svg); });}