2013-05-29 61 views
1

因此,我正在嘗試進行動態測驗,並且正在努力向我的無線電輸入添加文本。我使用for循環來製作幾個無線電輸入。我希望文本與每個廣播選擇都在同一行上,但我無法完成此任務。jQuery-將文本添加到每個無線電輸入的同一行

當我使用append()它創建一個新行,然後添加文本。

for (j = 0; j < 5; j++) { 
      $('#target').append('<input type="radio" name="radioName"/>') 
      $('#target').append('<p>My text here</p>'); 

當我使用label for HTML屬性,它增加了在所有的收音機都結束的文本。

for (j = 0; j < 5; j++) { 
      $('#target').append('<input type="radio" name="radioName"/>').after("<label for='radio'>text here</label>"); 

這是我的jsfiddle表示例如:http://jsfiddle.net/tCkuF/2/

理想我想添加表示對象的文本,以便它作爲測驗取自動改變的變量。

回答

2

推薦使用表元素在這種情況下

<div id="container"> 
    <div id="question"></div> 
    <div id="target"> 
     <ul id="options"> 

     </ul> 
    </div> 
</div> 

也給風格

#options{ 
    list-style:none; 
    list-style-type:none; 
} 

然後加入li元素。給予適當的id使用for屬性

var $li = $("<li>").appendTo("#options"); 
$li.append('<input id="option' + (j+1) + '" type="radio" name="question' + i + '" value="' + allQuestions[i].correctAnswer + '"/>'); 
$li.append("<label for='option" + (j+1) + "'>test: label for adds all to the end </label>"); 

演示:http://jsfiddle.net/tCkuF/6/

2

所需輸出增加一個額外的<br/>每行

$('#target').append('test append creates a line space<br/>'); 

檢查演示可以通過簡單地將radio &圍繞一個div包裝來實現'標籤'。選中此out

$(function() { 
var i = 0; 
var allQuestions = [{ 
    question: "What is 4x6?", 
    choices: [46, 15, 25, 24], 
    correctAnswer: 3 
}, { 
    question: "What is 21x 21?", 
    choices: [441, 2121, 388], 
    correctAnswer: 0 
}, { 
    question: "Which number is prime?", 
    choices: [1, 5, 10, 39], 
    correctAnswer: 1 
}, { 
    question: "What is 65/5", 
    choices: [3, 31, 12, 13, 21], 
    correctAnswer: 3 
}]; 

function populateQuestion() { 
    $("#question").text(allQuestions[i].question); //add question 
    var $target = $('#target'), 
     j = 0; 
    //add radio and answer choices 
    for (j; j < allQuestions.length; j++) { 

     (function (idx) { 

      var html = '<div class="answerRow"><input class="answerRadio" type="radio" name="question' + idx + '" value="' + allQuestions[idx].correctAnswer + '"/><label class="answerRadioLabel" for="question' + idx + '">test: label for adds all to the end </label>'; 
      $target.append(html); 
     })(j); 
    } 
} 

populateQuestion(); 


}); //onload jQuery close 
相關問題