开发者

How to change the src of a img with its alt?

Is 开发者_如何学Pythonthere way to change the image src attribute with its alt attribute on load of the image?

I want the script to automatically change the image's source to the image's alt.

Before

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

After

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


You could use 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;
    }
}();

Don't forget to wrap it into script tags if you're implementing it in HTML files:

<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>


Try this:

var change = function() {
    var imgs = document.images || document.getElementsByTagName('img');
    for (var i = 0; i < imgs.length; i++) {
        imgs[i].src = imgs[i].alt;
    }
}

DEMO


First of all, give the id of the image so img tag will look like this:

<img id="img1" src="" alt="myimage.jpg" onload = "changesource()"/>

Now write a JavaScript function like this:

function changeSrc()
{
    var img = document.getElementById("img1");
    img.src =img.alt;
}

Now call this function on the load of image like this:

onload = "changeSrc()"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜