javascript - 如何向通过单击按钮显示的图片添加替代文本?

标签 javascript html

有没有办法添加单独的替代文本(例如“图片 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/

相关文章:

html - 从中心开始的 CSS 线性渐变

javascript - 在部分之间创建 flex 的叠加层。

javascript - 在canvas.js气泡图上加载文本内容值

javascript - phonegap XMLHttpRequest responseText 在 android 中为空,但在 iphone 中包含数据

javascript - 上传照片

javascript - javascript 中的 ul 和 li

html - 使用不同的 DIV 将 CSS 向右推 300 像素

javascript - 动态创建的PHP数组字段不使用mysql将数据保存在表中

javascript - 我不明白 jQuery.data() 方法

html - html右侧的额外空间?