1

HTML 入力名を JavaScript オブジェクトに変換することに関連する問題があります。たとえば、次の入力があります。

<input type="checkbox" name="product[1]">
<input type="checkbox" name="product[2]">

そして私はjavascriptコードを持っています:

var data = {};
$('input').each(function(){
    // need to do something like 
    data[$(this).attr('name')] = $(this).attr('checked');
})

このようなデータ オブジェクトを取得することを期待しています。

data = {
    product: {
        1: 'checked',
        2: 'checked'
    }
}

これは正規表現を使わなくても可能ですか?

4

3 に答える 3

0

変数をリテラル値に置き換えると、次のようになります。

data["product[1]"] = true;

角かっこは文字列内にあるため意味がないため、結果は得られません。

これを回避する方法があります。あなたは評価を使用することができます:eval("data."+this.name+" = "+(this.checked?"true":"false"));

ただし、eval避けるのが最善なので、これを試してください:

var m = this.name.match(/(.*)\[(\d+)\]/);
data[m[0]][m[1]] = this.checked;
于 2013-03-01T16:51:53.230 に答える
0

はい、概ね可能です。次のことができます。

var noregexp = $(this).attr('name').split("[");
if (noregexp.length==2) {
    //should be
    var the_name = noregexp[0];
    var the_index = noregexp[1].substr(0,noregexp[1].length-1); //this will get the index with removed ]
}

私はこれを心から作りました。それは美しい解決策ではありませんが、あなたが望むように正規表現のないものです。

于 2013-03-01T16:55:17.060 に答える
0

以下を使用して、必要な方法でデータ構造を取得できます。

var data = {product: []};
$('input').each(function(){
    data.product[$(this).attr('name').match(/product\[([\d]*)\]/)[1]] = $(this).prop('checked');
})
console.log(data);

このデモをチェック

于 2013-03-01T16:57:44.510 に答える