开发者

Automatically adding the 'alt' attribute to every image on a page

I have a requirement to add the alt attribute to each o开发者_运维技巧f the images on each of my web pages. The problem is that there are hundreds of images on some of those web pages.

Can anyone suggest an approach using JavaScript or jQuery that, for each image on a page, copies the name of the image (minus the extension) to a new alt attribute?

Before:

<img src="android.jpg width="100" height="50" />

After (exclude ".jpg"):

<img src="android.jpg width="100" height="50" alt="android" />


In jQuery:

$(document).ready(function() {
  $('img').each(function(){
    var $img = $(this);
    var filename = $img.attr('src')
    $img.attr('alt', filename.substring(0, filename.lastIndexOf('.')));
  });
});

You could ask before if alt attribute doesn't already exist by adding:

var attr = $(this).attr('alt');
    if (typeof attr == typeof undefined || attr == false) {


Here is a JavaScript approach:

function runScript() {
    for (i = 0; i < document.getElementsByTagName("img").length; i++) {
        document.getElementsByTagName("img")[i].setAttribute(
            "alt", document.getElementsByTagName("img")[i].src);
    }
}

Run the function runScript() once the page is loaded!


This script can help you to get your work handled. It will append the filename of image in alt attribute

<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js' type='text/javascript'/>  
 <script type='text/javascript'>  
 //<![CDATA[  
 $(document).ready(function() {  
  $('img').each(function(){  
   var $img = $(this);  
   var filename = $img.attr('src')  
   $img.attr('title', filename.substring((filename.lastIndexOf('/'))+1, filename.lastIndexOf('.')));  
   $img.attr('alt', filename.substring((filename.lastIndexOf('/'))+1, filename.lastIndexOf('.')));  
  });  
 });  
 //]]>  
 </script>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜