如何使用jquery选择具有或不具有特定'alt'属性的图像

问题描述 投票:3回答:3

我有很多.png图像,想要提供一个提到替代文本的提及名称,如果在alt标记中没有提到它应该显示'png-image'。

下面的代码只是将所有png图像的替换文字'png-image'。

假设我有一个图像的alt文本,即alt="facebook"它应该显示alt="facebook"代替alt="png-image"

通过View Source它显示alt="facebook"代替alt="png-image"

<script type="text/javascript">
    (function ($) {
        $(document).ready(function() {
            // apply Image alt attribute
            $('img[src$=".png"]').attr('alt', 'png-image');
        });
    }(jQuery));
</script>
javascript jquery jquery-selectors
3个回答
2
投票

您可以使用.each方法在.png末尾用src循环所有图像。在每个图像,您可以使用以下方法检查它是否具有alt属性:

if(!$(this).attr('alt'))

如果图像当前没有alt,则此if语句将运行,因此您可以将自己的alt属性添加到图像。

见下面的工作示例:

$(document).ready(function() {
  $('img[src$=".png"]').each(function() {
    if (!$(this).attr('alt')) // check if current image tag has alt attribute
      $(this).attr('alt', 'png-image'); // if it doesn't add 'png-image' alt attribute
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<img src="foo.png" /><br />
<img src="bar.png" alt="this is my own alt" /><br />
<img src="foo2.png" alt="this is my own alt2" /><br />
<img src="foo.png" />

这适用于未设置alt属性或设置为空的两种情况(即:alt=""


0
投票

您可以使用当前选择器添加[alt=""]选择器

(function($) {
  $(document).ready(function() {
    // apply Image alt attribute
    $('img[src$=".png"][alt=""]').attr('alt', 'png-image');

  });

}(jQuery));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src='https://images.pexels.com/photos/599708/pexels-photo-599708.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500' alt='image'>
<img src='https://fnetobits.s3.amazonaws.com/galleries/boyerfuneralhome/1819974/1138985594.png' alt=''>

0
投票

您可以在JQuery中使用基于属性的选择器来获取所有不具有alt属性的img标记,

$(document).ready(function() {
    $('img[src$=".png"][alt='']').attr('alt','png-image');
})
© www.soinside.com 2019 - 2024. All rights reserved.