使用javascript动态创建div元素

时间:2015-07-13 06:05:47

标签: javascript html dynamic

我正在尝试使用javascript动态创建html元素。例如,在我的“finalXML”文件中创建段落时,我使用以下语法:

function paragraph (finalXML, value)

{

var code1 = 'var para = document.createElement("p");
var t = document.createTextNode("This is the paragraph that should be displayed");
para.appendChild(t);
document.body.appendChild(para);'

return String(finalXML).replace(/add_paragraph_here/g,code1);
}

我如何使用单选按钮创建div,例如,使用相同的过程?任何人都可以用这种语法帮助我吗?

1 个答案:

答案 0 :(得分:0)

请参阅此示例:http://jsfiddle.net/kevalbhatt18/owuqm8j8/

 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);