有没有办法添加单独的替代文本(例如“图片 1/2 不可用”),以防图片无法显示?我如何更改此代码以允许这种情况发生?
(Sridhar 的代码)
<script type = "text/javascript">
function pic1()
{
document.getElementById("img").src = "picture 1 source";
}
function pic2()
{
document.getElementById("img").src ="picture 2 source";
}
</script>
<img src = "" id = "img"/> <input type="button" value="Show Picture
1" onclick="pic1()"/> <input type="button" value="Show Picture 2"
onclick="pic2()"/>
最佳答案
Is there a way to add separate alternate text (such as "picture 1/2 not available") in case a picture fails to display?
是的,这就是 alt
属性的用途 - 无论如何,它实际上是图像的必需属性。
您可以使用 .alt
设置图像的 alt 标签,如下所示:
var image = document.getElementById("img");
image.src = "Image src here"
image.alt = "Image alt here - if image failed to render, you will see this!"
假设您必须通过 JavaScript 来完成此操作。大多数人只是将其包含在 HTML 本身中:
<img src = "" id = "img" alt="Alternative text here!"/>
查看有关 alt
属性的更多信息 here 。
编辑:您可以考虑使用onerror
来表达德里克的观点:
"onerror allows for different alt text when an image is simply not found rendered or when the image is not found"
关于javascript - 如何向通过单击按钮显示的图片添加替代文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16583266/