将值存储在数组或来自jquery选择器的散列中以供重用

时间:2011-11-30 15:11:08

标签: javascript jquery

如何将值存储到数组或散列中以便单独调用而不添加单个标识符?

var myarray = [];
$(".express").each(function () {
  myarray.push($(this).text()); 
});

function flashEXPRESS() {
   $(".express").each(function () {
     if ($(this).text() == 'NEW') { $(this).text() = myarray[???]; }
     else { $(this).text() == 'NEW'}
   });
}
var flashEXPRESSid = 0;
flashEXPRESSid = setInterval("flashEXPRESS()",1000);

2 个答案:

答案 0 :(得分:2)

回调each会将索引作为第一个参数。这可能就是你所需要的。

$(".express").each(function (index) {
     if ($(this).text() == 'NEW') { $(this).text() = myarray[index]; }
     else { $(this).text() == 'NEW'}
});

答案 1 :(得分:0)

从评论中,如果你想让你的div更改,并添加,而不是搞砸你的数组索引,这样的事情可能会有效:

var myarray = {}; //object, not an array
$(".express").each(function () {
  var identifier = $(this).data("idforobject");
  myarray[identifier] = $(this).text(); 
});

function flashEXPRESS() {
   $(".express").each(function () {
     if ($(this).text() == 'NEW') { 
         $(this).text() = myarray[$(this).data("idforobject")]; 
     }
     else { $(this).text() == 'NEW'}
   });
}

然后在你的divs上:

<div class="express" data-idforobject="something unique">

只需将myarray重命名为其他内容,因为它不再是数组