由于.attr
刚刚获得一个属性 - the first one found by the jQuery selector - 你需要的元素来建立你的数组元素。要做到这一点的方法之一是.each
(你也可以使用.data
提取数据属性):
var position = new Array;
$('#ipadmenu > section').each(function() {
position.push($(this).data('order'));
});
alert(position[0]); // alerts "1"
这将是一个索引数组,不是关联数组。要建立其中的一个(在JavaScript是技术上的对象,而不是任何类型的数组)只是改变你的.each
环的内侧部分:
:
var position = {};
$('#ipadmenu > section').each(function(i) {
position["section"+i] = $(this).data('order');
});
生成的对象position
现在可以像访问
alert(position['section1']); // alerts "1"
一种不同的方法包括使用jQuery.map
,但因为这仅适用于阵列,而不是jQuery的对象,你需要使用jQuery.makeArray
到您的选择转换为真正的数组第一:
var position = $.map($.makeArray($('#ipadmenu > section')), function() {
return $(this).data('order');
}); // position is now an indexed array
这种方法在技术上比使用.each
短,但我觉得不太清楚。
'$(” #ipadmenu>部分') .attr('data-order')'已经返回一个你可以用''.each()'](http://api.jquery.com/jQuery.each/)解析的对象或者用''.eq ()'](http://api.jquery.com/eq/) – JMax
'array'在JavaScript中没有特殊含义。 –
so var position = $('#ipadmenu> section')。attr('data-order')。each;会返回正确的数组? – cmplieger