帮助循环属性并从数组中引用它们

Help looping through attributes and refrencing them from array

本文关键字:引用 数组 循环 属性 帮助      更新时间:2023-09-26

首先感谢您提供的帮助。

我有数组/循环问题。我试图循环通过下面的div和存储属性在一个数组稍后引用。当我在浏览器中测试警报时,我没有得到属性的值。我现在只使用data-id属性进行测试,但希望通过引用索引/键来访问所有属性。我花了两天时间尝试了所有我能想到的方法。For循环,$.each(),等等…

<div class="image_fullsize" data-count="1" data-id="183" data-title="Title of Gallery" data-description="description 1" data-photo="http://to-image1.jpg" data-credit="photo-credit1"></div>
<div class="image_fullsize" data-count="2" data-id="184" data-title="Title of Gallery" data-description="description 2" data-photo="http://to-image2.jpg" data-credit="photo-credit2"></div>
<div class="image_fullsize" data-count="3" data-id="185" data-title="Title of Gallery" data-description="description 3" data-photo="http://to-image3.jpg" data-credit="photo-credit3"></div>

这是我的javascript

var myArray = [];
$('.image_fullsize').each(function(index) {
   myArray += $(this).attr('data-id');
    //alert (myArray);
  });
alert (myArray[2]);

你可以这样做:

var myArray = [];
$('.image_fullsize').each(function(index) {
   myArray.push($(this).data('id'));
  });
alert (myArray[2]);

在javascript数组中有一个push()方法,它将你传递给它的内容添加到数组

提琴在这里:http://jsfiddle.net/NbKhT/