2011-10-19 41 views
0

使用这个语法:选择元素的数组,并使用它们

var position = array($('#ipadmenu > section').attr('data-order')); 

我不能让我的代码工作。我之前从来没有使用过数组,所以在如何使用它们的时候会丢失一些数组。 (特别是在jQuery中)。

我将如何制作所有节元素的数组,并将数据顺序的值关联到该列表。例如:

first section - data-order:1 
second section - data-order:2 

等,然后使用该信息后。

谢谢!

+1

'$(” #ipadmenu>部分') .attr('data-order')'已经返回一个你可以用''.each()'](http://api.jquery.com/jQuery.each/)解析的对象或者用''.eq ()'](http://api.jquery.com/eq/) – JMax

+0

'array'在JavaScript中没有特殊含义。 –

+0

so var position = $('#ipadmenu> section')。attr('data-order')。each;会返回正确的数组? – cmplieger

回答

2

由于.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短,但我觉得不太清楚。

+0

非常感谢你的真棒帖子:) – cmplieger

1

的Javascript:

var orders = []; 
$('#ipadmenu > section').each(function() { 
    orders.push($(this).data('order')) 
}); 

HTML:

<div id="ipadmenu"> 
    <section data-order="1">1</section> 
    <section data-order="2">2</section> 
</div> 
0

你会想要做这样的事情:

// Get the elements and put them in an array 
var position = $('#ipadmenu section').toArray(); 
console.log(position); 

// Loop through the array 
for (var i = 0; i < position.length; i++){ 
    // Display the attribute value for each one 
    console.log("Section " + i + ": " + $(position[i]).attr('data-order')); 
} 

工作示例这里:http://jsfiddle.net/U6n8E/3/

相关问题