【问题标题】:Jquery array iteration with images带有图像的 Jquery 数组迭代
【发布时间】:2018-03-23 13:41:43
【问题描述】:
var imgLink = ['ONYX', 'Bristol_Blue_B_002_10', 'Oakhampton_B_001_10-1', 'Quartet_KitchenCountertop_500x342', 'Eternal-Serena_RS11277_Silestone-Kitchen', 'zodiaq_provence_kitchen_2200x1467-b94f5-1', 'Eternal-Serena_RS11277_Silestone-Kitchen-1', 'Ecobycosentino-', 'Hanstone', 'IceStone-Forest-Fern-Shadowlight-Vignette-Kitchen-Countertop', 'RS833_Silversilk_OA-hpr-copy_CMYK', 'scalea'];

    var imgArray = [];

jQuery.each(imgLink, function(i){
    var img = jQuery('<img/>')

    .attr("src", "http://www.link.com/wp-content/uploads/2017/10/" +imgLink[i]+ ".jpg")
    imgArray.push(img[i]);  
});
console.log(imgArray);

大家好,我上面有一个代码,我的目标是制作一个带有属性的数组图像,但现在的结果是

JSFiddle

谁能告诉我我做错了什么,谢谢!

【问题讨论】:

  • 只有第一个有效,因为当 i 为 0 时,您将 DOM 节点推入数组中,img[1] 及以后没有意义。您应该改用imgArray.push(img)

标签: javascript jquery arrays push each


【解决方案1】:

你有一个错字。

imgArray.push(img[i]);  

应该是:

imgArray.push(img); // <-- img is not an array

【讨论】:

    【解决方案2】:

    var imgLink = ['ONYX', 'Bristol_Blue_B_002_10', 'Oakhampton_B_001_10-1', 'Quartet_KitchenCountertop_500x342', 'Eternal-Serena_RS11277_Silestone-Kitchen', 'zodiaq_provence_kitchen_2200x1467-b94f5-1', 'Eternal-Serena_RS11277_Silestone-Kitchen-1', 'Ecobycosentino-', 'Hanstone', 'IceStone-Forest-Fern-Shadowlight-Vignette-Kitchen-Countertop', 'RS833_Silversilk_OA-hpr-copy_CMYK', 'scalea'];
    
    var imgArray = [];
    
    jQuery.each(imgLink, function(key, value) {
      var img = jQuery('<img/>').attr("src", "http://www.link.com/wp-content/uploads/2017/10/" + value + ".jpg")
    
      // uncomment below for img 
      //imgArray.push(img);
    
      // just html for testing
      imgArray.push(img[0]);
    });
    console.log(imgArray);
    &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

    【讨论】:

      猜你喜欢
      • 2014-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-28
      • 2014-05-04
      • 1970-01-01
      • 1970-01-01
      • 2021-12-09
      相关资源
      最近更新 更多