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