javascript Jquery 数组 - 设置和加载值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12072244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery array - set and load values
提问by dtjmsy
I am having 2 divs:
我有 2 个 div:
<div id="player" class="setPlayers">value1</div>
<div id="player2" class="setPlayers">value2</div>
All I want to do is to set the value1 and value2 of the divs to an array for reading later on; I tried out this code, but doesn' t work:
我想要做的就是将 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());
});?
what' s wrong according to you ?,cheers
你怎么了?,干杯
回答by Mark Broadhurst
Using your code as a start I came up with:
使用您的代码作为开始,我想出了:
$(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);
});
});
?
?
Few too many alerts and debug for my liking.
很少有我喜欢的警报和调试。
If you just want to fill the array then this will do:
如果您只想填充数组,则可以这样做:
$(function(){
var array = $('.setPlayers').map(function() { return $(this).text()); }).get();
});
?
回答by Danil Speransky
Try this (see demo: http://jsfiddle.net/GcjgH/):
试试这个(见演示:http: //jsfiddle.net/GcjgH/):
var array = $('.setPlayers').map(function() {
return $(this).text();
}).get();
alert(array[0]);
alert(array[1]);
?
回答by Ohad
The correct syntax would be $('.setPlayers').each(function(){ ... });
正确的语法是 $('.setPlayers').each(function(){ ... });
In the context of the question:
在问题的背景下:
$('.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]);
}
etc.
等等。
回答by sp00m
This should work:
这应该有效:
var array = new Array();
$(".setPlayers").each(function() {
array.push($(this).text());
});