使用javascript的动态字典

使用javascript的动态字典,javascript,jquery,asp.net-mvc-3,dynamic,dictionary,Javascript,Jquery,Asp.net Mvc 3,Dynamic,Dictionary,我试图在客户端填充dictionary对象,我可以将其传递给我的Action方法。我能够用硬编码的值构建dictionary对象,但是我希望基于DOM元素动态创建它 下面是如何编写代码的示例: <input type="text" id="t1" class="textClass" /> <input type="text" id="t2" class="textClass" /> <input type="text" id="t3" class="textClas

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

下面是如何编写代码的示例:

<input type="text" id="t1" class="textClass" />
<input type="text" id="t2" class="textClass" />
<input type="text" id="t3" class="textClass" />
<input type="text" id="t4" class="textClass" />
<input type="text" id="t5" class="textClass" />

<input type="button" id="btnSubmit" value="Submit" />
这就是我想要构建字典的方式,但我无法弄清楚如何使用索引和DOM元素来创建字典键和值。如果我按照下面写的方式写,它就不会构成字典

<script type="text/javascript">

        $('.textClass').each(function (index) {
            dictionary = {

                '[' + index '].Key': $(this).attr('id'), 
                '[' + index '].Value': $(this).val(), 

            };


</script>

$('.textClass')。每个(函数(索引){
字典={
“['+索引'].Key':$(this.attr('id'),
“['+索引'].Value':$(this.val(),
};

有人能告诉我我做错了什么吗?

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

var dictionary = {};
dictionary['[' + index + '].Key'] = $(this).attr('id');
您当前正在为每次迭代覆盖dictionary变量。在您的场景中,您可能需要以下内容:

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

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

var dictionary = {};
dictionary['[' + index + '].Key'] = $(this).attr('id');
您当前正在为每次迭代覆盖dictionary变量。在您的场景中,您可能需要以下内容:

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

谢谢。我对它进行了硬编码,看它是否有效。你的答案很有效。再次感谢。谢谢。我对它进行了硬编码,看它是否有效。你的答案很有效。再次感谢。