Pez*_*kow 5 javascript each foreach jquery scope
我正在尝试构建一个包含每个表单元素的所有值的数组.警报只能找到,但在console.log数据是空的,我不明白javascript中的作用域是如何工作的?
var data = new Array();
$("#page2 input").each(function(index) {
alert($(this).attr('id'));
data[$(this).attr('id')] = $(this).val();
});
Run Code Online (Sandbox Code Playgroud)
非常感谢你的时间,
有一点需要知道Array,JavaScript中只能有正整数索引(实际上它们被视为字符串).
为字符串分配字符串时,您要为其分配属性Object.
你可能想要这样的东西......
var data = {};
$("#page2 input").each(function() {
data[this.id] = this.value;
});
Run Code Online (Sandbox Code Playgroud)
如果你只想要id属性.
var data = $("#page2 input").map(function() {
return this.id;
}).get();
Run Code Online (Sandbox Code Playgroud)