2017-12-09 6 views
-2

JSで簡単なテストを作成しようとしています。 4つのラジオボタンを作成してhtmlに追加する機能があります。私はそれをn回と呼んだとき、同じ4つのラジオボタンをdivに追加して、4番目の質問から1つの回答を選択しようとすると、最初のdiv/questionから答えが選択されます。Javascript変数スコープとの混乱

function getRandom(min, max) { 
 
    return Math.random() * (max - min) + min; 
 
} 
 

 
function test_2() { 
 

 
    var a = getRandom(0, 10) - 5; 
 

 
    while (a == 0) 
 
    a = getRandom(0, 10) - 5; 
 

 
    var b = getRandom(0, 10) - 5; 
 

 
    //create the div in which i add the radio buttons 
 
    var div = document.createElement('div'); 
 
    div.setAttribute('class', 'parent'); 
 
    div.setAttribute('id', '2'); 
 

 
    document.body.appendChild(div); 
 

 
    //create the radio button and set its attributes 
 
    var radio1 = document.createElement('input'); 
 
    var label1 = document.createElement('label'); 
 
    label1.innerHTML = a * 4 + b; 
 
    label1.setAttribute('for', 'radio1'); 
 
    radio1.setAttribute('type', 'radio'); 
 
    radio1.setAttribute('value', a * 4 + b); 
 
    radio1.setAttribute('id', 'radio1'); 
 
    radio1.setAttribute('name', 'answ'); 
 
    radio1.innerHTML = a * 4 + b; 
 

 
    //add it to the div 
 
    div.appendChild(radio1); 
 
    div.appendChild(label1); 
 
} 
 

 
test_2();

+0

コード例は、質問の関連部分を含むように単純化してください。 –

+1

すべての 'div'と' input [type = radio] '要素には同じ' id'値が与えられています。 'id'はドキュメント内で一意でなければなりません。 –

+0

@ YotamSalmonコードを簡略化する必要はありません。ここでは余計なことはありません。それどころか、シナリオを再現できるように、関連するコードを追加する必要があります。 –

答えて

0

name属性は、それぞれの質問に対して異なっている必要があります:すべての "ラジオ・ボタン・パック" test_2()が発生しているので

おそらく起こって
<form> 
    <!-- Question 01 --> 
    <fieldset id="group1"> 
     <input type="radio" value="" name="group1"> 
     <input type="radio" value="" name="group1"> 
    </fieldset> 

    <fieldset id="group2"> 
    <!-- Question 02 --> 
     <input type="radio" value="" name="group2"> 
     <input type="radio" value="" name="group2"> 
     <input type="radio" value="" name="group2"> 
    </fieldset> 
</form> 
0

(同じnameプロパティの値は、 answ)。このような 迅速な解決がtest2にパラメータとしてnameを送信することですので、あなたの「名前空間」あなたのラジオボタン:

function test_2(name) { 

    var a = getRandom(0, 10) - 5; 

    ... 

    radio1.setAttribute('name', name + '-answ'); 

    ... 

}

この方法で、あなたは、ループ内で、この関数を呼び出している場合インデックスのnameパラメータとして渡して、名前の一意性を保証することができます。