0

私は以下のようなJavaScriptコードを持っています

function createArray()
{
    var myArr = new Object();
    myArr[0] = createSubArray('apple');
    myArr[1] = createSubArray('Mango');
    myArr[2] = createSubArray('Pineapple');
    myArr[3] = createSubArray('Grape'); */
    document.getElementById("a").innerHTML = JSON.stringify(myArr);
    return myArr;
} 

function createSubArray(name){
    var arr = new Object();
    elems = document.getElementsByName(name);
    for (var i=0;i<elems.length;i++){
        if (elems[i].checked){
            arr[name] =  elems[i].value;
            arr['price'] =  elems[i].getAttribute('data-price');
        }
    }
    return arr;

}

この createArray() 関数を動的に変更する必要がありますが、これがどのように可能かはわかりません。これが私が試した私のコードです

function createArray()
{
    var myArr = new Object();
    elems = document.getElementsByTagName("input");
     for (var i=0;i<elems.length;i++){
        var elmcheck = elems[i].getAttribute('type');
        //alert(elmcheck);
        if (elems[i].checked)
        {
         alert("A Radio Is Check "+elems[i].getAttribute('name'));
         myArr[i] = createSubArray(elems[i].getAttribute('name'));
        }
    }
    document.getElementById("a").innerHTML = JSON.stringify(myArr);
    return myArr;
} 

function createSubArray(name){
    var arr = new Object();
    elems = document.getElementsByName(name);
    for (var i=0;i<elems.length;i++){
        if (elems[i].checked){
            arr[name] =  elems[i].value;
            arr['price'] =  elems[i].getAttribute('data-price');
        }
    }
    return arr;

}

しかし、それは機能していません..

4

1 に答える 1

0

これを試してみてください

function createArray()
{
    var myArr = new Object();
    var elems = document.getElementsByTagName("input");
     for (var i=0;i<elems.length;i++)
     {
       if (elems[i].checked)
       {
          myArr[i] = createSubArray(elems[i].getAttribute('name'));
       }
     }
    document.getElementById("a").innerHTML = JSON.stringify(myArr);
    return myArr;
} 

function createSubArray(name){
    var arr = new Object();
    var elems = document.getElementsByName(name);
    for (var i=0;i<elems.length;i++)
    {
        if (elems[i].checked)
        {
            arr[name] =  elems[i].value;
            arr['price'] =  elems[i].getAttribute('data-price');
        }
    }
    return arr;
}
于 2012-09-18T06:04:31.543 に答える