jQuery-在不使用类或父级的情况下单独处理每个img元素

jQuery - Treat each img element individually without using class or parent

本文关键字:处理 单独 情况下 元素 img jQuery-      更新时间:2023-09-26

我想做的是让src中的图像维度根据图像的宽度属性进行调整。(请注意,该维度在url中定义,"s1600"为原始大小,"s320"为320像素宽等)。

我450多篇文章中的图片没有类属性。

我已经用我有限的jQuery知识走到了这一步,但现在我陷入了困境。正如你所看到的,我的代码正在计算它在页面上找到的第一个图像,并将这些维度应用于其他图像,从而导致其他img元素的分辨率不高。

$('img').each(function(){
    var $this = $(this)
    var imgWidth = $("img").width() + 100
  $this.attr('src',$this.attr('src').replace('s1600','s' + imgWidth))
}) 

jsFiddle:http://jsfiddle.net/w576y236/

此处:JSFiddle

HTML

<img width="200" src="http://3.bp.blogspot.com/-NX_ClFb2-Uk/UGJHjrprEAI/AAAAAAAAARk/HD7o4dbV7Wo/s1600/bookshelves-at-the-library_w482_h725.jpg" />
<br/>
<img width="640" src="http://3.bp.blogspot.com/-NX_ClFb2-Uk/UGJHjrprEAI/AAAAAAAAARk/HD7o4dbV7Wo/s1600/bookshelves-at-the-library_w482_h725.jpg" />

JavaScript

$('img').each(function(){
    $(this).attr('src',$(this).attr('src').replace('s1600','s' + parseFloat($(this).css('width'))));
});