【发布时间】:2021-04-12 14:39:22
【问题描述】:
function altTextToImageCaption() {
let imgs = document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
var att = imgs[i].attributes.getNamedItem('alt');
if (!att) continue;
var alt = att.value;
if (!alt) continue;
if (!alt.startsWith('Fig ')) continue;
var cap = document.createElement('div');
cap.setAttribute('class', 'imageCaption');
cap.appendChild(document.createTextNode(alt));
document.body.insertBefore(cap, imgs[i].nextSibling);
}
}
<body onload="altTextToImageCaption()">
<h1>Image Caption No Workie</h1>
<img src="https://www.easyrgb.com/look/home_logo.png" alt="Fig 1. First caption.">
<div>
<img src="https://www.easyrgb.com/look/home_logo.png" alt="Fig 2. Second caption.">
</div>
</body>
我正在尝试提出一个 jscript 函数,该函数在 html 文档中的所有图像下方插入标题文本,其中包含以“Fig”开头的 alt 属性。似乎可以工作,除非img 节点位于div 或span 内。在这种情况下有一个例外:
Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node."
【问题讨论】:
-
imgs[i].parentNode.insertBefore(cap, imgs[i]);也许? -
@AlonEitan 很好,将图像标题置于图像之上。我在下面需要它。