2012-09-19 22 views
0

我想填充客戶端的字典對象,我可以傳遞給我的Action方法。我能夠使用硬編碼值構建字典對象,但是我想基於DOM元素動態創建它。使用javascript的動態字典

這裏是如何的代碼如下所示:

<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" /> 

這裏是JavaScript函數與硬編碼值。我正在循環所有具有textClass的文本框。這工作正常,我能夠看到Action方法參數中的字典項目。

<script type="text/javascript"> 

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

       '[0].Key': 'k1', 
       '[0].Value': 'v1', 

      }; 


</script> 

這是我要如何構建字典,但我無法弄清楚如何使用索引和DOM元素創建詞典鍵和值。如果我寫下我寫下的方式,它不會構造字典。

<script type="text/javascript"> 

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

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

      }; 


</script> 

有人可以請指出我在這裏做錯了什麼?

回答

5

爲了能夠從字符串來構造鍵,你需要對其進行相應設置:

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(); 
}); 
+0

謝謝。我對它進行了硬編碼,看看它是否有效。你的回答很好。再次感謝。 – Asdfg

0
$('.textClass').each(function(index) { 

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

});