Javascript 如何使用jquery添加img标签的alt属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10414733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:12:30  来源:igfitidea点击:

How to add an alt attribute of img tags with jquery

javascriptjqueryhtml

提问by user1301411

I've put a google map in a page and it makes lots of img tags without the alt attribute, how can I add the alt for each img in a div in jquery, what's I gotta make instead of :

我在页面中放置了一个谷歌地图,它制作了很多没有 alt 属性的 img 标签,如何在 jquery 的 div 中为每个 img 添加 alt,我必须制作什么而不是:

$('#map_canvas > img[alt]').attr('image');

Thanks

谢谢

回答by VisioN

To set alternative text to all the images:

为所有图像设置替代文本:

$('#map_canvas > img').attr('alt', 'Alternative text');

To set alternative text to images that does not have altattribute:

为没有alt属性的图像设置替代文本:

$('#map_canvas > img:not([alt])').attr('alt', 'Alternative text');

回答by Crontab

Try:

尝试:

$("#map_canvas > img:not([alt])").attr("alt", "<YOURALTTEXT>");

回答by Andrea Turri

This work:

这项工作:

$('#map_canvas').find('img:not([alt])').attr('alt', 'Alt text');

回答by Richard

You could do:

你可以这样做:

$('#map_canvas > img[alt=""]').each(function()
{
    $(this).attr('alt', $(this).attr('src');
});

This would find all images within #map_canvasthat do not have an alttag, and then set the alttag to be the same as the image src.

这将找到#map_canvas其中没有alt标签的所有图像,然后将alt标签设置为与图像相同src

Alternatively, I would recommend:

或者,我建议:

$('#map_canvas > img[alt=""]').attr('alt', 'Alt text');

As this will only add alt tags to images that don't have one.

因为这只会向没有 alt 标签的图像添加 alt 标签。

回答by Bibin Velayudhan

$('#map_canvas > img').attr('alt', 'alt_text');