我想分配一个JS中的关联数组风格的对象,但它失败,说'task.id'是未定义的。为什么是这样?JavaScript中的关联风格数组?
var response = Object();
$('.task-list').each(function() {
response[this.id][$('#' + this.id).sortable('toArray')];
});
我想分配一个JS中的关联数组风格的对象,但它失败,说'task.id'是未定义的。为什么是这样?JavaScript中的关联风格数组?
var response = Object();
$('.task-list').each(function() {
response[this.id][$('#' + this.id).sortable('toArray')];
});
您正在将对象引用为二维数组。
你应该这样做更多的是这样的:
var response = {};
$(".task-list").each(function() {
response[this.id] = $(this).sortable('toArray');
}
此外,当你说的错误是“task.id是不确定的”,你的意思是“this.id是未定义”?如果您选择基于类的元素,则可能没有明确的ID。
<span class="task-list">myTask</span>
您可能要包括ID:
<span class="task-list" id="myTask">myTask</span>
您正试图访问您尚未创建的属性。尽管实际情况并不清楚你在示例中要做什么。我假设你想将response[this.id]
的值设置为$('#' + this.id).sortable('toArray')
?
试试这个:
var response = {};
$('.task-list').each(function() {
response[this.id] = $(this).sortable('toArray');
});
也改变了它使用$(this)
而不是$('#' + this.id)
,因为它是清洁海事组织。