Jquery数组-设置和加载值

Jquery array - set and load values

本文关键字:加载 设置 数组 Jquery      更新时间:2023-09-26

我有两个div:

<div id="player" class="setPlayers">value1</div>
<div id="player2" class="setPlayers">value2</div>

我所要做的就是将div的值1和值2设置为一个数组,以便以后读取;我试过这个代码,但不起作用:

var array = new Array();
$.each($('.setPlayers'), function(key, object) {
    console.log(index + ':' + value);
    array.push(value);
    alert(value);
});
$.each(array, function(index, value) {
    console.log(index + ':' + value);
    console.log(index + ':' + $(this).val());
});​

你说怎么了?,欢呼

以您的代码为起点,我提出了:

$(function(){
  var array = [];
  $('.setPlayers').each(function(index) {
      console.log(index + ':' + $(this).text());
      array.push($(this).text());
      alert($(this).text());
  });
  $.each(array, function(index) {
      console.log(index + ':' + this);
      console.log(index + ':' + this);
  });
});

很少有太多的警报和调试符合我的喜好。

如果你只想填充数组,那么这就可以了:

$(function(){
  var array = $('.setPlayers').map(function() { return $(this).text()); }).get();
});
​

试试这个(见演示:http://jsfiddle.net/GcjgH/):

var array = $('.setPlayers').map(function() {
  return $(this).text();
}).get();
alert(array[0]);
alert(array[1]);
​

正确的语法应该是$('.setPlayers').each(function(){ ... });

在问题的背景下:

$('.setPlayers').each(function(){
     console.log($(this).attr("id")+':'+$(this).text());
     array.push($(this).text());
     alert($(this).text());
});
for (var i=0; i<array.len; i++){
    console.log(arr[i]);
}

等等。

这应该有效:

var array = new Array();
$(".setPlayers").each(function() {
    array.push($(this).text());
});