2011-10-19 57 views
4

我想创建一个数组,分配给一个div元素,push()一个值,并在稍后阶段再次检索它。jquery - 如何设置和检索数组存储使用数据()

谁能告诉我,我错过了什么...:

// set Array 
// $(this) is the HTML-element which should get array assigned 
var stack = [], 
    stack.push('#'+$(this).find(':jqmData(role="page")').attr('id')), 

$(this).data(stack); 

使用

console.log($(this).data(stack)); 

我找回了整个HTML元素,而

console.log($(this).data(stack[0] OR stack.length)); 

不起作用。

如何访问我(推测是)推入阵列的元素?

回答

3

您需要命名您的数据。例如:

$("div").data("stack", []); //This sets the data key "stack" to an empty array 
$("div").data("stack").push(123); //This retrieves the array and pushes a number to the array 
console.log($("div").data("stack")); //This prints the array 
+0

有趣的方法,+1 –

+0

非常感谢你。完美的作品! – frequent

1

要分配数据到一个元素,你必须给它一个索引的关键。

PUT

$(this).data('stack', stack); 

GET

var stack = $(this).data('stack'); 
+0

也感谢,但我使用Xeon06的建议 – frequent

0

数据需要一个键,值对。你没有通过钥匙。

$(this).data('stack', stack); 

然后检索它:

$(this).data('stack'); 
相关问题