2014-11-25 2 views
1

Проблема в том, что переключатель не появился. И я смущен концепцией создания узла, создания текста узла, создания значения узла, createElement и т. Д. Таких концепций.Радио-кнопка не получается из JS-файла

Вот мой код, http://jsfiddle.net/vadjn2an/

Вот моя функция,

function displayQuestion() { 
    var question = document.getElementById("question"); 
    question.textContent = questionPool[currentQuestion].question; 
    var numberOfChoices = questionPool[currentQuestion].choices.length; 
    for(var i=0; i < numberOfChoices; i++) { 
     var label = document.createElement('label'); 
     var radio = document.createElement('input'); 
     radio.setAttribute('type', 'radio'); 
     radio.setAttribute('name', 'choice'); 
     radio.setAttribute('value', 'questionPool[currentQuestion].choices[i]'); 
     label.appendChild(radio); 
     question.appendChild(label); 
     label.innerHTML = questionPool[currentQuestion].choices[i] + "<br>"; 
    } 

Спасибо за вашу помощь заранее,

+0

Если проблема в том, что не появляется кнопка радио, чем is't, потому что после добавления его маркировать вы делаете: label.innerHtml =». .."Ведьма переписывает you'r кнопку – Rasalom

+0

@Rasalom Я сделал заказ, как это сейчас, но все еще есть ошибки, – Yumiko

+0

@Rasalom label.innerHTML = questionPool [currentQuestion] .choices [я] +."
«; этикетки. appendChild (radio); question.appendChild (label); – Yumiko

ответ

1

Причина, по которой не будет отображаться потому, что вы заменить лейбла внутреннийHTML в
вопросPool [текущийQuestion] .соты [i] + <br>.

, когда вы добавляете радио в ярлыке, innerHTML лейбла стал "< вход > ... </вход >" , но тогда вы просто заменить его в

questionPool [currentQuestion] .choices [я] + "<br> ".

просто Подведите label.innerHTML = ... перед label.appendChild может решить вашу ситуацию.

вот немного изменить ответ, не используя innerHTML и внешнийHTML.

function displayQuestion() { 
    var question = document.getElementById("question"), 
     currentQuestion = 0, 
     numberOfChoices = questionPool[currentQuestion].choices.length; 
    question.textContent = questionPool[currentQuestion].question; 
    question.appendChild(document.createElement('br')); 
    for(var i=0; i < numberOfChoices; i++) { 
     var label = document.createElement('label'), 
      radio = document.createElement('input'), 
      textNode= document.createTextNode(questionPool[currentQuestion].choices[ i]), 
      lineBreakNode = document.createElement("br"); 
     radio.setAttribute('type', 'radio'); 
     radio.setAttribute('name', 'choice'); 
     radio.setAttribute('value',  'questionPool[currentQuestion].choices[i]'); 
     label.appendChild(radio); 
     label.appendChild(textNode); 
     label.appendChild(lineBreakNode);   
     question.appendChild(label); 
    } 
} 

http://jsfiddle.net/vadjn2an/9/

иметь радиошоу перед лейблом, я использую label.outerHTML вводить его innerHTML лейбла

function displayQuestion() { 
    var question = document.getElementById("question"); 
    var currentQuestion = 0; 
    var numberOfChoices = questionPool[currentQuestion].choices.length; 
    question.textContent = questionPool[currentQuestion].question; 
    question.appendChild(document.createElement('br')); 
    for(var i=0; i < numberOfChoices; i++) { 
     var label = document.createElement('label'); 
     var radio = document.createElement('input'); 
     radio.setAttribute('type', 'radio'); 
     radio.setAttribute('name', 'choice'); 
     radio.setAttribute('value',  'questionPool[currentQuestion].choices[i]'); 
     label.innerHTML = radio.outerHTML + questionPool[currentQuestion].choices[i] + "<br/>"; 
     question.appendChild(label); 
    } 
}  

http://jsfiddle.net/vadjn2an/8/

+0

Нет, это не сработает. Если я переведу его, на первом ярлыке будет отсутствовать радиокнопка, а в конце есть дополнительная радиокнопка. – Yumiko

+0

, так что вы хотите радиопередачу перед ответом? – SansWord

+0

Да, но ваш jsfiddle все еще не отображается правильно. – Yumiko

0

Вам нужно присоединить radio button к question , пожалуйста, измените кодовую строку

из

label.appendChild(radio); 

в

question.appendChild(radio); 

Надеется, что это помогает!

+0

Это все равно приведет к пропуску HTML-текста. – Yumiko

1

Попробуйте ввести код.

createTextNode

var questionPool = [ 
    { 
    question: " Which is the biggest city in China?", 
    choices: ["Beijing", "Shanghai", "Guangzhou"], 
    correctAnswer: 1, 
    } 
]; 

var question = document.getElementById("question"); 
var questionPool = questionPool[0]; 
question.textContent = questionPool.question; 

for(var i=0;i<questionPool.choices.length;i++){ 
    var label = document.createElement('label'); 

    var radio = document.createElement('input'); 
    radio.setAttribute('type', 'radio'); 
    radio.setAttribute('name', 'choice'); 
    radio.setAttribute('value', questionPool.choices[i]); 
    label.appendChild(radio); 

    var txt = document.createTextNode(questionPool.choices[i]); 
    label.appendChild(txt); 

    question.appendChild(label); 
} 
+0

Спасибо @ jckim0414 Это работает правильно. Я выясню формат материала ... Спасибо за вашу помощь снова. – Yumiko

1

Вот полный ответ на ваш вопрос. HTML часть

<form> 
    <label id="question">Question:</label><br /> 
    <div id="answersBox"> 
    </div> 
    <input type="button" value="save" /> 
</form> 

Javascript часть

var questionPool = [ 
    { 
    question: " Which is the biggest city in China?", 
    choices: ["Beijing", "Shanghai", "Guangzhou"], 
    correctAnswer: "Beijing", 
    } 
]; 

var currentQuestion = questionPool[0].question; 

document.getElementById('question').innerHTML = currentQuestion; 

choiceList(); 
function choiceList() { 
    var question=questionPool[0]; 
    for (choice in question.choices) {   

    var choiceSelection = document.createElement('input'); 
    var choiceLabel = document.createElement('label'); 



    choiceSelection.setAttribute('type', 'radio'); 
    choiceSelection.setAttribute('name', 'choice'); 

    choiceLabel.innerHTML=question.choices[choice]; 
    choiceLabel.setAttribute('for', question.choices[choice]); 

    document.getElementById('answersBox').appendChild(choiceSelection); 
     document.getElementById('answersBox').appendChild(choiceLabel); 
    } 

} 
choiceList(); 
+0

Это выглядит круто ... @Ankush Bhan – Yumiko

+0

Пожалуйста, выберите правильный ответ, чтобы другие пользователи могли сэкономить время! –

Смежные вопросы