Asd*_*dfg 0 javascript jquery dictionary dynamic asp.net-mvc-3
我试图在客户端填充字典对象,我可以传递给我的Action方法.我能够使用硬编码值构建字典对象,但是我想基于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" />
Run Code Online (Sandbox Code Playgroud)
这是具有硬编码值的JavaScript函数.我正在循环通过所有的文本框textClass.这工作正常,我能够在Action方法参数中看到字典项.
<script type="text/javascript">
$('.textClass').each(function (index) {
dictionary = {
'[0].Key': 'k1',
'[0].Value': 'v1',
};
</script>
Run Code Online (Sandbox Code Playgroud)
这是我想要构建字典的方式,但我无法弄清楚如何使用索引和DOM元素来创建字典键和值.如果我按照下面的方式编写,它就不构造字典.
<script type="text/javascript">
$('.textClass').each(function (index) {
dictionary = {
'[' + index '].Key': $(this).attr('id'),
'[' + index '].Value': $(this).val(),
};
</script>
Run Code Online (Sandbox Code Playgroud)
有谁可以请指出我在这里做错了什么?
为了能够从字符串构造键,您需要相应地设置它们:
var dictionary = {};
dictionary['[' + index + '].Key'] = $(this).attr('id');
Run Code Online (Sandbox Code Playgroud)
您当前正在为每次迭代覆盖字典变量.在您的场景中,您需要以下内容:
var dictionary = {};
$('.textClass').each(function (index) {
dictionary['['+index+'].Key'] = $(this).attr('id');
dictionary['['+index+'].Value'] = $(this).val();
});
Run Code Online (Sandbox Code Playgroud)