如何为没有ID的图像添加替代文本。

huangapple go评论65阅读模式
英文:

How to add alt text to images without an ID

问题

需要为各种没有ID或其他标识图像的图像添加alt文本,是否可以根据图像文件名为每个图像添加alt文本?

这是我开始编写的代码示例,但显然不起作用,我甚至不确定我是否朝着正确的方向前进。任何帮助将不胜感激。

<script>
document.onload = function(){
  img.setAttribute('src', 'icons-vegan.png');
  img.setAttribute('alt', 'Vegan Icon');
  img.setAttribute('title', 'Vegan Icon'); 
}	
document.onload = function(){
  img.setAttribute('src', 'icons-gluten.png');
  img.setAttribute('alt', 'Gluten Icon');
  img.setAttribute('title', 'Gluten Icon'); 
}	
</script>
英文:

I need to add alt text to various images which do not have IDs or anything else to identify the images from one another other there the image file names.

Is there a way to add alt text to each image based on what the image file name is?

Here's an example of the code I started working on, but it obviously doesn't work and I'm not even sure I am heading in the right direct. Any help would be much appreciated.

&lt;script&gt;
document.onload = function(){
  img.setAttribute(&#39;src&#39;, &#39;icons-vegan.png&#39;);
  img.setAttribute(&#39;alt&#39;, &#39;Vegan Icon&#39;);
  img.setAttribute(&#39;title&#39;, &#39;Vegan Icon&#39;); 
}	
document.onload = function(){
  img.setAttribute(&#39;src&#39;, &#39;icons-gluten.png&#39;);
  img.setAttribute(&#39;alt&#39;, &#39;Gluten Icon&#39;);
  img.setAttribute(&#39;title&#39;, &#39;Gluten Icon&#39;); 
}	
&lt;/script&gt;

答案1

得分: 0

以下是翻译好的代码部分:

// 基本解决方案,考虑到缺乏详细上下文而做出了很多假设

var images = document.getElementsByTagName("img");
for (var image of images) {
    image.setAttribute("alt", image.src);
}

1) 通过简单获取所有标签为 "<img>" 的元素列表来获取所有图像

2) 对于每个图像将其 alt 属性设置为其 src 属性
英文:

Basic solution making lots of assumptions given the lack of detailed context

var images = document.getElementsByTagName(&quot;img&quot;);
for(var image of images)
{
 image.setAttribute(&quot;alt&quot;, image.src)
}
  1. Get all images by simply getting a list of all elements of tag "<img>"

  2. For each image, set its alt = its src

答案2

得分: 0

我们可以简单地选择 HTML 中的所有 img 标签并动态更新 alt 和 title。

// 找到所有 img 标签并将列表转换为数组
const imgs = Array.from(document.getElementsByTagName("img"))

// 循环处理每个图像并处理 `src` 属性
imgs.forEach(img => {
  const altText = img.src
    .split("/") // 以 "/" 分隔字符串
    .at(-1) // 获取最后一个段落
    .split(".").slice(0, -1).join(".") // 移除文件扩展名
    // 移除破折号并大写首字母
    .split("-").map(s => s[0].toUpperCase() + s.slice(1).toLowerCase()).join(" ")

  // 添加属性
  img.setAttribute("alt", altText)
  img.setAttribute("title", altText)
})

演示:

<!-- 开始片段: js hide: true console: true babel: false -->

<!-- 语言: lang-js -->

    // 找到所有 img 标签
    const imgs = document.getElementsByTagName("img")

    console.log("添加 alt 前:", [...imgs])

    // 循环处理每个图像并处理 `src` 属性
    Array.from(imgs).forEach(img => {
      const altText = img.src
        .split("/") // 以 "/" 分隔字符串
        .at(-1) // 获取最后一个段落
        .split(".").slice(0, -1).join(".") // 移除文件扩展名
        // 移除破折号并大写首字母
        .split("-").map(s => s[0].toUpperCase() + s.slice(1).toLowerCase()).join(" ")

      // 添加属性
      img.setAttribute("alt", altText)
      img.setAttribute("title", altText)
    })

    console.log("添加 alt 后:", [...imgs])

<!-- 语言: lang-html -->

    <img src="icons-vegan.png" />
    <img src="icons-gluten.png" />
    <div>
      <img src="/something/something-else.png?12345" />
    </div>

<!-- 结束片段 -->
英文:

We can simply select all the img tags from our HTML and update the alt and title dynamically.

// find all img tags and convert the list to an array
const imgs = Array.from(document.getElementsByTagName(&quot;img&quot;))

// loop through each image and process the `src` attribute
imgs.forEach(img =&gt; {
  const altText = img.src
    .split(&quot;/&quot;) // split the string into segments delimited by &quot;/&quot;
    .at(-1) // get last segment
    .split(&quot;.&quot;).slice(0, -1).join(&quot;.&quot;) // remove file extension
    // remove dashes and capitalize
    .split(&quot;-&quot;).map(s =&gt; s[0].toUpperCase() + s.slice(1).toLowerCase()).join(&quot; &quot;)

  // add properties
  img.setAttribute(&quot;alt&quot;, altText)
  img.setAttribute(&quot;title&quot;, altText)
})

Demo:

<!-- begin snippet: js hide: true console: true babel: false -->

<!-- language: lang-js -->

// find all img tags
const imgs = document.getElementsByTagName(&quot;img&quot;)

console.log(&quot;before adding alt:&quot;, [...imgs])

// loop through each image and process the `src` attribute
Array.from(imgs).forEach(img =&gt; {
  const altText = img.src
    .split(&quot;/&quot;) // split the string into segments delimited by &quot;/&quot;
    .at(-1) // get last segment
    .split(&quot;.&quot;).slice(0, -1).join(&quot;.&quot;) // remove file extension
    // remove dashes and capitalize
    .split(&quot;-&quot;).map(s =&gt; s[0].toUpperCase() + s.slice(1).toLowerCase()).join(&quot; &quot;)

  // add properties
  img.setAttribute(&quot;alt&quot;, altText)
  img.setAttribute(&quot;title&quot;, altText)
})

console.log(&quot;after adding alt:&quot;, [...imgs])

<!-- language: lang-html -->

&lt;img src=&quot;icons-vegan.png&quot; /&gt;
&lt;img src=&quot;icons-gluten.png&quot; /&gt;
&lt;div&gt;
  &lt;img src=&quot;/something/something-else.png?12345&quot; /&gt;
&lt;/div&gt;

<!-- end snippet -->

答案3

得分: 0

选择所有图像并循环它们以获取其src属性。一旦获取到它们,您可以为循环内的每个图像设置alt属性。以下是一个示例:

const images = document.querySelectorAll('img');

for (let img of images) {
  switch (img.getAttribute('src')) {
    case 'banana.png':
      img.alt = '香蕉';
      break;
    case 'apple.png':
      img.alt = '苹果';
      break;
    case 'orange.png':
      img.alt = '橙子';
      break;
  }
}
<img src="banana.png">
<img src="apple.png">
<img src="orange.png">
英文:

Select all images and loop them to get their src attribute. Once you have them, you can set the alt attribute for each image which is inside that loop. Here is an example:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const images = document.querySelectorAll(&#39;img&#39;);

for (let img of images) {
  switch (img.getAttribute(&#39;src&#39;)) {
    case &#39;banana.png&#39;:
      img.alt = &#39;Banana&#39;;
      break;
    case &#39;apple.png&#39;:
      img.alt = &#39;Apple&#39;;
      break;
    case &#39;orange.png&#39;:
      img.alt = &#39;Orange&#39;;
      break;
  }
}

<!-- language: lang-html -->

&lt;img src=&quot;banana.png&quot;&gt;
&lt;img src=&quot;apple.png&quot;&gt;
&lt;img src=&quot;orange.png&quot;&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月6日 06:33:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76410395.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定