【问题标题】:Cycling through img src attributes in array with jQuery使用jQuery循环遍历数组中的img src属性
【发布时间】:2011-11-23 04:07:49
【问题描述】:

我正在构建一个响应式网站,并且在一个特定页面上,我试图让移动设备(宽度为 480 或更小)不下载特定图像。我知道我已经很接近了,我会在代码之后告诉你原因。

HTML:

<div class="index-section">
  <p><img class="scale-with-grid" alt="" /></p>
  <p><a href="#">A Letter from Person 1&nbsp;<span class="triangle">&#9654;</span></a></p>
</div>

<div class="index-section">
  <p><img class="scale-with-grid" alt="" /></p>
  <p><a href="">A Letter from Person 2&nbsp;<span class="triangle">&#9654;</span></a></p>
</div>

<div class="index-section">
  <p><img class="scale-with-grid" alt="" /></p>
  <p><a href="">A Letter from Person 3&nbsp;<span class="triangle">&#9654;</span></a></p>
</div>

<div class="index-section">
  <p><img class="scale-with-grid" alt="" /></p>
  <p><a href="">A Letter from Person 4&nbsp;<span class="triangle">&#9654;</span></a></p>
</div>

基本上是 4 个几乎相同的 div。这是 jQuery:

$(document).ready(function() {

var imgPath = '_/img/'

var $winWidth = $(window).width();

var $indexSection = $('.index-section p img');

if ( $winWidth <= 480 ) {
    $indexSection.attr('src','');
    $indexSection.css('display','none');
    } else {
        var imgSrc = [ "keith-index.jpg", "derek-video.jpg", "bar-chart.jpg", "honor-roll.jpg" ];

        jQuery.each(imgSrc, function(value){
            $indexSection.attr('src',imgPath + value);
        });
   }
});

我把它放在头部(在 jQuery 库之后),以便它添加 src 作为其呈现 HTML。这适用于 iPhone(或宽度小于 480 像素的 Firefox)并且不会加载图像,所以这很棒。

问题是,在 480 像素以上,当我尝试循环浏览图像时,它几乎可以正常工作,因为 Firefox 的控制台告诉我它无法加载“http://myurl.com/_/img/0 .jpg”,它告诉我它几乎正确地连接,但是由于某种原因,它打印的是数组的索引,而不是值(我认为)。

我需要的是,如果浏览器的宽度超过 480,则将 url 打印为每个图像的 src 属性(“myurl.com/_/img/keith-index.jpg”和其他三个在它们各自的 div 中),以便图像在桌面浏览器上加载。

感谢您的帮助。

【问题讨论】:

    标签: jquery arrays each


    【解决方案1】:

    对于jQuery.each,第一个回调参数是集合中的索引,第二个参数是值。

    jQuery.each(imgSrc, function(index, value){
        $indexSection.attr('src',imgPath + value);
    });
    

    编辑: 哎呀...我错过了您正在尝试做的一个更根本的问题。

    $indexSection 是一个 jQuery 对象,其中包含所有您正在使用的图像。当您调用$indexSection.attr 时,您将同时为所有四个图像设置属性。您为每个 imgSrc 值执行此操作,因此所有四个图像的 src 属性最终都设置为最后一个 imgSrc 值。

    相反,您希望遍历 img 标记,并从 imgSrc 访问每个图像的正确值。

    $indexSection.each(function(index) {
        $(this).attr('src', imgPath + imgSrc[index]);
    });
    

    【讨论】:

    • 感谢您的回复。奇怪的行为。在 Firefox 中,我第一次在其中添加“索引”时,它为每个图像添加了数组中的最后一个值,甚至没有加载其他图像(根据 Firebug)。我刷新并加载了其他图像,但继续显示数组中所有图像的最后一个图像。看看:nickcox.me/dev/annual-report/index.html
    • 我标记对了。谢谢你的帮助。 (我也感谢您的解释,而不仅仅是回答!)但是,您能解释为什么index 有效吗?我以为我读错了并输入了value,效果也很好。我本来希望 index 打印 0、1、2、3 和 value 给我图像。该数组的索引不只是数字位置吗?为什么我不想要这些值?
    猜你喜欢
    • 1970-01-01
    • 2014-11-26
    • 2014-08-15
    • 1970-01-01
    • 2018-04-13
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多