如何使用JS为单选按钮创建textNode?



我正在尝试用JavaScript制作一个单选按钮。使用HTML很容易,即<input type="radio" name="sType" value="m">MALE,到目前为止,使用JS我可以创建<input type="radio" name="sType" value="m">但我不知道如何为其创建MALE文本节点。我还想将此形式附加到带有id='user_input'的身体的 3rddiv 元素中,那么它的 DOM 导航应该是什么? 这是我的代码:

document.getElementsById('user_input').childNodes[0].appendChild(f);
var f = document.createElement("form");
f.setAttribute("id", "myForm");
f.setAttribute('method',"post");
f.setAttribute('action',"ride_test.php");
var radio1 = document.createElement("input"); //input element, text
radio1.setAttribute("id","radio1");
radio1.setAttribute('type',"radio");
radio1.setAttribute('name',"sType");
radio1.setAttribute('value',"m");
f.appendChild(radio1);       

如果要向单选按钮添加说明,则应创建一个label并在其中插入单选按钮的说明。

let f = document.createElement("form");
let radio1 = document.createElement("input"); //input element, text
radio1.setAttribute("id","radio1");
radio1.setAttribute('type',"radio");
radio1.setAttribute('name',"sType");
radio1.setAttribute('value',"m");
let label = document.createElement('label');
label.textContent = "MALE";
f.appendChild(radio1);
f.appendChild(label);
document.body.appendChild(f)

您还可以创建文本节点并在输入后追加,但不建议使用此选项:

//The same as above
let desc = document.createTextNode("MALE")
f.appendChild(radio1)
f.appendChild(desc);
document.body.appendChild(f)`

小提琴:https://jsfiddle.net/dpu54as9/

输入标签是自动封闭的标签,不应包含任何文本。您需要在旁边使用标签标签(您可以查看此链接(,例如:

<input type="radio" name="sType" id="radio1" value="m"/>
<label for="radio1">MALE</label>

要在代码中执行此操作,只需创建一个新的标签元素,设置其文本并附加到表单中:

var f = document.createElement("form");
f.setAttribute("id", "myForm");
f.setAttribute('method',"post");
f.setAttribute('action',"ride_test.php");

var radio1 = document.createElement("input"); //input element, text
var label1 = document.createElement("label");
// link label to input through id
label1.setAttribute("for", "radio1");
label1.innerHTML = "MALE";
radio1.setAttribute("id","radio1");
radio1.setAttribute('type',"radio");
radio1.setAttribute('name',"sType");
radio1.setAttribute('value',"m");
f.appendChild(radio1);
f.appendChild(label1);

请注意,ID 是唯一的,这意味着 DOM 上不能同时具有多个具有相同名称的 ID。实现所需目标的最佳方法是将user_input更改为类(不是唯一的(,然后附加到 DOM,如下所示:

document.body.getElementsByClassName('user_input')[2].appendChild(f);

最新更新