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

store values in a array or hash from jquery selector for reuse

本文关键字:选择器 jquery 存储 数组      更新时间:2023-09-26

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

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

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

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

从注释来看,如果您希望允许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'}
   });
}

Then on yourdiv:

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

myarray重命名为其他东西,因为它不再是数组