【问题标题】:Detect and Add dynamically width and height and alt attribute to all images检测并动态添加所有图像的宽度和高度以及 alt 属性
【发布时间】:2014-10-02 17:41:45
【问题描述】:

我正在尝试为网页上没有这些属性的每个图像动态获取和添加宽度、高度和 alt 属性。但它只检测第一个图像宽度高度 alt 属性并将它们添加到所有图像中。

$(document).ready(function() {
    var width = $('img').width();
    var height = $('img').height();
    var image_width = $('img').attr('width');
    var image_height = $('img').attr('height');
    var image_alt = $('img').attr('alt');
    if (typeof image_width === 'undefined' || image_width === false && typeof image_height === 'undefined' || image_height === false) {
        $('img').attr('width', width).attr('height', height);
    }
    if (typeof image_alt === 'undefined' || image_alt === false) {
        $('img').attr('alt', 'image');
    }
});

http://jsfiddle.net/a9zsqxov/

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    您需要遍历您的 img 标签并在每个标签上执行您的逻辑。 "$('img').width()" 只返回它找到的第一张图片的值(正如你发现的那样)。

    例如:

    $('img').each(function() {
      var $img = $(this),
          width = $img.width(),
    
      // ..the rest of your logic here..
    });
    

    【讨论】:

    【解决方案2】:

    您的逻辑没问题,但您必须遍历所有 img 元素,而不仅仅是第一个元素。这是一个简单的例子:

        $(document).ready(function() {
            $('img').each(function() {
                var width = $(this).width();
                var height = $(this).height();
                $(this).attr('width', width);
                $(this).attr('height', height);
            });
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-26
      • 2016-10-29
      • 1970-01-01
      • 2018-01-13
      • 2010-12-17
      • 1970-01-01
      • 2011-01-01
      相关资源
      最近更新 更多