1

我有 2 个 div:

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

我要做的就是将 div 的 value1 和 value2 设置为一个数组,以便以后读取;我尝试了这段代码,但不起作用:

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());
});​

你怎么了?,干杯

4

4 回答 4

5

使用您的代码作为开始,我想出了:

$(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);
  });
});

​</p>

很少有我喜欢的警报和调试。

如果您只想填充数组,则可以这样做:

$(function(){
  var array = $('.setPlayers').map(function() { return $(this).text()); }).get();
});
​
于 2012-08-22T11:46:59.667 回答
3

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

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

alert(array[0]);
alert(array[1]);
​
于 2012-08-22T11:41:27.583 回答
0

正确的语法是$('.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]);
}

等等

于 2012-08-22T11:39:47.647 回答
0

这应该有效:

var array = new Array();
$(".setPlayers").each(function() {
    array.push($(this).text());
});
于 2012-08-22T11:40:44.723 回答