Home > Web Front-end > HTML Tutorial > How to add alt attribute to all img tags on web content

How to add alt attribute to all img tags on web content

伊谢尔伦
Release: 2016-12-03 11:37:19
Original
2410 people have browsed it

How to add the alt attribute to all img tags on the webpage
Adding the alt attribute to the img tag is to better identify the search engine and tell it what it is, but sometimes when the page content is very large, some img tags The alt attribute will be omitted
, which is very annoying to check, or if you want to layout more keywords on the page, you can use a piece of Jquery code to fill these shortcomings. The principle is this, first get the page The total number of all img tags, and then use a for loop to find whether there is an alt attribute in each img tag. If not, add the alt attribute you defined. If it exists, skip it. The following code :

var alt="图片名称"; //定义要添加的alt属性名
var imgsize = $('body img').size(); //得出img标签的总数量
for (i = 0; i < imgsize; i++) {
//如果当前img标签的alt属性不存在,则添加
 if (!$(&#39;body img&#39;).eq(i).attr(&#39;alt&#39;)) {
 $(&#39;body img&#39;).eq(i).attr(&#39;alt&#39;, alt)
 }
}
Copy after login

If you don’t want the name to be too single, you can fill in a few more, save them in an array, and then use a random function to calculate the number. Example:

$(document).ready(function() {
 var alt=new Array("图片名称","图片名称一","图片名称二","图片名称三");
 var altsize=alt.length; //计算数组长度
 var imgsize = $(&#39;body img&#39;).size(); //得出img标签的总数量
 for (i=0; i<imgsize; i++) {
 //如果当前img标签的alt属性不存在,则添加
 if (!$(&#39;body img&#39;).eq(i).attr(&#39;alt&#39;)) {
 //Math.floor(Math.random()*altsize) 获取一个均衡的随机数
 $(&#39;body img&#39;).eq(i).attr(&#39;alt&#39;, alt[Math.floor(Math.random()*altsize)]);
 }
 }
});
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template