检测并动态添加宽度和高度以及alt属性到所有图像

时间:2014-08-09 09:29:15

标签: javascript jquery

我正在尝试为不具有这些属性的网页上的每个图像动态添加宽度,高度和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/

2 个答案:

答案 0 :(得分:1)

您需要遍历img标记并在每个标记上执行逻辑。 “$('img')。width()”只返回它找到的第一个图像的值(如你所知)。

例如:

$('img').each(function() {
  var $img = $(this),
      width = $img.width(),

  // ..the rest of your logic here..
});

答案 1 :(得分:1)

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

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