0

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

ハードコードされた値を持つ 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>

誰かが私がここで間違っていることを指摘してもらえますか?

4

2 に答える 2

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();
});
于 2012-09-19T07:07:06.410 に答える
0
$('.textClass').each(function(index) {

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

});
于 2012-09-19T07:13:35.923 に答える