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

时间:2011-07-19 20:35:34

标签: javascript jquery loops

首先感谢您提供的任何帮助。

我有一个数组/循环问题。我正在尝试遍历下面的div并将属性存储在稍后要引用的数组中。当我在浏览器中测试我的警报时,我没有得到我的属性的值。我现在只使用data-id属性测试它,但希望通过引用索引/键来访问所有属性。我已经在这里工作了2天,尝试了我能想到的一切。 for循环,$ .each()等...

HTML

<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]);

1 个答案:

答案 0 :(得分:3)

你可以这样做:

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

  });

alert (myArray[2]);

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

在这里摆弄:http://jsfiddle.net/NbKhT/