找到alt属性不带双引号的图片标签并替换为空双引号

问题描述 投票:0回答:1

<img src="first.jpg" alt="first" width="500" height="600" />
<img src="second.jpg" alt width="500" height="600" />
<img src="third.jpg" alt="third" width="500" height="600" />
<img src="fourth.jpg" alt width="500" height="600" />
<img src="fifth.jpg" alt="" width="500" height="600" />

查找具有不带双引号的 alt 属性的图像标签,并替换为空双引号以实现 ADA 可访问性,我需要 jquery 来查找第二个和第四个 img 标签,替换为 alt="" 就像第五个一样

我尝试了下面的方法,但没有成功

$(function() {
  $("img").each(function() {
    if (this.alt) {
      console.log(this.alt);
    } else {
      $(this).attr('alt', "");
    }
  });
});

jquery accessibility ada
1个回答
0
投票

您需要确保定位正确的元素并使用正确的属性。这是代码的更正版本,用于查找第二个和第四个

img
标签并将其
alt
属性替换为空双引号:

$(function() {
  $("img").each(function(index) {
    if (index === 1 || index === 3) { // Select the second (index 1) and fourth (index 3) img tags
      $(this).attr('alt', "");
    }
  });
});

确保将此脚本放置在

<script>
标记内,并在将 jQuery 库包含在 HTML 文档中之后将其包含在内。此代码将迭代所有
img
标签并检查它们的索引。

© www.soinside.com 2019 - 2024. All rights reserved.