显示带有换行符的动态创建的单选按钮

时间:2015-07-28 19:14:20

标签: javascript html radio-button

我有一些代码可以使用javascript在html页面上动态创建单选按钮。我可以在哪里以及如何添加"<br>"以使单选按钮在生成的html页面上每行显示一个? 请通过以下链接查看jsfiddle。

http://jsfiddle.net/kevalbhatt18/owuqm8j8/

&#13;
&#13;
 var radio_home = document.getElementById("radio_home");

 function makeRadioButton(options) {
     var div = document.createElement("div");
     for (var i = 0; i < options.length; i++) {
         var label = document.createElement("label");
         var radio = document.createElement("input");
         radio.type = "radio";
         radio.name = options[i].name;
         radio.value = options[i].value;
         label.appendChild(radio);
         label.appendChild(document.createTextNode(options[i].text));
         div.appendChild(label);
         }
       radio_home.appendChild(div);
 }
 var options = [{
     name: "first",
     value: "yes",
     text: "yes"
 }, {
     name: "first",
     value: "no",
     text: "no"
 }]
  var options2 = [{
     name: "second",
     value: "ohhh yes",
     text: "ohhh yes"
 }, {
     name: "second",
     value: "ohhh no",
     text: "ohhh no"
 }]
makeRadioButton(options);
makeRadioButton(options2);
&#13;
<div id="radio_home"></div>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

要添加<br>标记,您只需使用document.createElement功能,就像使用无线电按钮一样,并在

之后直接使用它。
function makeRadioButton(options) {
    var div = document.createElement("div");
    for (var i = 0; i < options.length; i++) {
        var label = document.createElement("label");
        var radio = document.createElement("input");
        radio.type = "radio";
        radio.name = options[i].name;
        radio.value = options[i].value;
        label.appendChild(radio);
        label.appendChild(document.createTextNode(options[i].text));
        div.appendChild(label);

        //if we are on the last itteration there is no need to create another <br>
        if(i+1<options.length)div.appendChild(document.createElement('br'));
    }
    radio_home.appendChild(div);
}

更新了demo

答案 1 :(得分:0)

要获得所需的结果,您甚至不需要<br>。只需在for循环中创建div,然后将其附加到循环内的包含父级。您需要将您的功能更新为以下

function makeRadioButton(options) {

  for (var i = 0; i < options.length; i++) {
     var div = document.createElement("div"); // moved inside the loop
     var label = document.createElement("label");
     var radio = document.createElement("input");
     radio.type = "radio";
     radio.name = options[i].name;
     radio.value = options[i].value;
     label.appendChild(radio);
     label.appendChild(document.createTextNode(options[i].text));
     div.appendChild(label);
     radio_home.appendChild(div); // moved inside the loop
  }
}

供参考 - http://jsfiddle.net/owuqm8j8/2/

答案 2 :(得分:0)

如果您只想一个接一个地显示单选按钮,您可以使用css的display属性并将其添加到标签中。 Hers是更新的fiddle,代码如下:

label
{display:block;}
相关问题