javascript - 如何使用 alt 更改 img 的 src?

标签 javascript html image

有没有办法在加载图像时使用其 alt 属性更改图像 src 属性?

我希望脚本自动将图像的源更改为图像的 alt。

之前

<img src="" alt="exe">

之后

<img src="exe" alt="exe">

最佳答案

你可以使用 JavaScript:

// Execute function on load through self-invocation
var switchAlt = function() {
    // Get all images on the document
    var images = document.getElementsByTagName('img');

    // Count the number of image elements and switch alt and src
    var i = images.length;
    while (i--) {
        images[i].src = images[i].alt;
    }
}();

如果您在 HTML 文件中实现它,请不要忘记将它包装到脚本标签中:

<script type="text/javascript">
// Execute function on load through self-invocation
var switchAlt = function() {
    // Get all images on the document
    var images = document.getElementsByTagName('img');

    // Count the number of image elements and switch alt and src
    var i = images.length;
    while (i--) {
        images[i].src = images[i].alt;
    }
}();
</script>

关于javascript - 如何使用 alt 更改 img 的 src?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4841400/

相关文章:

javascript - 使用 jQuery 获取 CSS 变换属性

javascript - 你能在不同的渲染和上下文中重用 React 元素吗?

javascript - 如何在 Jade 编译之前将 Javascript 对象包含在 Jade 模板中

javascript - 如何在提交时使用 jQuery 替换表单中的信息

html - <cite> 作为语义标记的一部分

c# - 使用 FileSystemWatcher 时 c# GUI 中的内存不足异常 - 多线程

image - 取消 Docker 镜像标签而不删除它?

javascript - 如何使用关闭按钮创建此多个动态 id 特定的 Accordion ?

c# - 在上传期间调整和优化网页图像的最佳类别是什么?

html - 文本溢出省略号