我想用附件数组的索引 0 替换第一个 img 标签的 src,用索引 1 替换第二个标签,依此类推,不使用 jQuery。存储在变量中的 html。
var body="<div dir="ltr">
text above image
<div>
<img src="cid:ii_ksc42giw0" alt="IMG_20210814_124816.jpg" width="407"
height="542"><br>
<img src="cid:ii_ksc41siq0" alt="IMG_20210814_124816.jpg" width="407"
height="542"><br>
</div>
<div>
text below image
</div>
</div>"
var attachments = ['https://some-random-url-1', 'https://some-random-url-2']
使用正则表达式尝试处理 HTML 很容易出错。相反,使用解析器。您似乎是在浏览器中执行此操作,因此您可以使用DOMParser
:
const doc = new DOMParser().parseFromString(body, "text/html");
const images = doc.querySelectorAll("img");
for (let i = 0, len = Math.min(attachments.length, images.length); i < len; ++i) {
images[i].src = attachments[i];
}
现场示例:
var body=`<div dir="ltr">
text above image
<div>
<img src="cid:ii_ksc42giw0" alt="IMG_20210814_124816.jpg" width="407"
height="542"><br>
<img src="cid:ii_ksc41siq0" alt="IMG_20210814_124816.jpg" width="407"
height="542"><br>
</div>
<div>
text below image
</div>
</div>`;
var attachments = ['https://some-random-url-1', 'https://some-random-url-2'];
const doc = new DOMParser().parseFromString(body, "text/html");
const images = doc.querySelectorAll("img");
for (let i = 0, len = Math.min(attachments.length, images.length); i < len; ++i) {
images[i].src = attachments[i];
}
// ...put `doc` in the document, or use `outerHTML` if you
// need an HTML string from the result
console.log(doc.body.innerHTML);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句