简体   繁体   English

放<img>带有 JavaScript 的 alt 标签

[英]Set <img> alt tag with JavaScript

I know how to set an ALT tag on an <img> if I have the class or globally to all the images on the page, however how can I do it to a specific image that doesn't have an id or class?我知道如何在<img>上设置 ALT 标签,如果我有类或全局到页面上的所有图像,但是如何对没有 id 或类的特定图像执行此操作? Can I use the parent DIV somehow to reference the image and add an alt tag?我可以以某种方式使用父 DIV 来引用图像并添加 alt 标签吗?

<div id="table_processing">
    <img src="processing_report.gif"> Loading Report List...
</div>

I'd recommend using document.querySelector() , which allows you to select the image using CSS (jQuery-like) selectors.我建议使用document.querySelector() ,它允许您使用 CSS(类 jQuery)选择器选择图像。

Like this:像这样:

var image = document.querySelector("#table_processing img");

and then you can set the alt attribute with:然后您可以使用以下命令设置alt属性:

image.alt = "Our New Alt Text";

or或者

image.setAttribute("alt", "our New Alt Text");

Here's a demo:这是一个演示:

 var image = document.querySelector("#table_processing img"); image.alt = "Our New Alt Text";
 <div id="table_processing"> <img src="http://via.placeholder.com/350x150"> Loading Report List... </div>

if you use jQuery, you could use the ID from the parent element like this:如果你使用 jQuery,你可以像这样使用来自父元素的 ID:

$('#table_processing img').attr('alt', 'your text here');

This "css selector" will get all images inside the div with the id "table_processing" and sets the alt tag.这个“css 选择器”将获取 div 中所有带有 id 为“table_processing”的图像并设置 alt 标签。

Pure/True/Real/Faster JavaScript Solution:纯/真/真实/更快的JavaScript解决方案:

function setAlt()
{
    var div = document.querySelector("#table-processing");
        var image = div.querySelector("img");
            image.setAttribute("alt", "something");
}

JQuery 允许您使用有效的 css 选择器,因此您可以使用它:

$('#table_processing img').attr('alt', <text>);

I hate to keep plugging jQuery, but here is a very good example of automating missing alt tags with generic info, this is something I do to patch for WCAG AA compliance until we can edit all the content.我讨厌继续插入 jQuery,但这里有一个很好的例子,它使用通用信息自动丢失 alt 标签,这是我为 WCAG AA 合规性而做的修补工作,直到我们可以编辑所有内容。

$("img:not([alt])").attr({ alt: "your alt text", role: "presentation" });
$("iframe:not([title])").attr({ title: "your iframe title" });

This looks for images without alt attributes, adds it and adds the value "your alt text here" along with a role for screen readers, but you can remove that.这将查找没有 alt 属性的图像,添加它并添加值“您的 alt 文本”以及屏幕阅读器的角色,但您可以删除它。 IO. IO。 also do the same for iframes and embeds that may be third parties that are out of compliance.也对可能是不合规的第三方的 iframe 和嵌入执行相同的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM