首先需要找到站点中的所有img
$("#body").find(img)
然后检查 img 是否具有“alt”属性,如果 image 具有该属性,它将被转义,如果没有或 alt 为空,则会从列表或数组中随机添加一个字符串到 img。
我现在必须在函数中使用 .each() 一些方法,但我是 jquery 的新手,所以一点帮助将是完美的。
首先需要找到站点中的所有img
$("#body").find(img)
然后检查 img 是否具有“alt”属性,如果 image 具有该属性,它将被转义,如果没有或 alt 为空,则会从列表或数组中随机添加一个字符串到 img。
我现在必须在函数中使用 .each() 一些方法,但我是 jquery 的新手,所以一点帮助将是完美的。
var arr = ['hello', 'hi', 'yo'];
$('#body img').each(function() {
if ( ! $(this).attr('alt'))
$(this).attr('alt', arr[Math.round(Math.random() * (arr.length - 1)))]);
});
您可以使用一个选择器完成所有操作:
$("#body img[alt!='']").each(function(){
// What you want here...
});
或这个:
$("#body img[alt!=''][alt]").each(function(){
取决于 DOM 结构。
或者有一个filter
功能:
$("#body img").filter(function(){
return this.alt;
}).each(function(){
// What you want here...
});
如果你想用一个来做这一切each
,你可以使用这个:
$("#body img").each(function(){
if (this.alt)
// Do something.
else
// Do something else.
});
这应该可以帮助您入门:
$("#body img").each(function(){
var $this = $(this);
if (!$this.attr("alt")){
//do something
}
});
Object.keys($('body').find('img')).map((item)=>{
return $('body').find('img')[item].alt
})
通过这种方法,您可以获得所有为空的图像 alt,并且您将获得所有没有 alt 属性的图像标签。