Jquery 数组 - 设置和加载值

dtj*_*msy 1 html javascript jquery dom

我有 2 个 div:

<div id="player" class="setPlayers">value1</div>
<div id="player2" class="setPlayers">value2</div>
Run Code Online (Sandbox Code Playgroud)

我想要做的就是将 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());
});?
Run Code Online (Sandbox Code Playgroud)

你怎么了?,干杯

Mar*_*rst 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);
  });
});
Run Code Online (Sandbox Code Playgroud)

?

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

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

$(function(){
  var array = $('.setPlayers').map(function() { return $(this).text()); }).get();
});
?
Run Code Online (Sandbox Code Playgroud)