使用javascript的动态字典

我试图在客户端填充字典对象,我可以传递给我的Action方法。 我能够使用硬编码值构建字典对象,但是我想基于DOM元素动态创建它。

以下是如何编写代码:

      

这是具有硬编码值的JavaScript函数。 我正在遍历所有具有textClass的文本框。 这工作正常,我能够在Action方法参数中看到字典项。

  $('.textClass').each(function (index) { dictionary = { '[0].Key': 'k1', '[0].Value': 'v1', };  

这是我想要构建字典的方式,但我无法弄清楚如何使用索引和DOM元素来创建字典键和值。 如果我按照下面的方式编写,它不构造字典。

  $('.textClass').each(function (index) { dictionary = { '[' + index '].Key': $(this).attr('id'), '[' + index '].Value': $(this).val(), };  

有人可以指点我在这里做错了什么吗?

为了能够从字符串构造键,您需要相应地设置它们:

 var dictionary = {}; dictionary['[' + index + '].Key'] = $(this).attr('id'); 

您当前正在为每次迭代覆盖字典变量。 在您的场景中,您需要以下内容:

 var dictionary = {}; $('.textClass').each(function (index) { dictionary['['+index+'].Key'] = $(this).attr('id'); dictionary['['+index+'].Value'] = $(this).val(); }); 
 $('.textClass').each(function(index) { dictionary = {}; dictionary['[' + index + '].Key'] = $(this).attr('id'); dictionary['[' + index + '].Value'] = $(this).val(); });