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

问题描述 投票:0回答:1

我试图用JavaScript制作一个单选按钮。使用HTML很容易,即到目前为止<input type="radio" name="sType" value="m">MALE和JS都可以创建<input type="radio" name="sType" value="m">,但是我不知道如何创建MALE文本节点,这是我的代码。我也想在主体的第三个div元素中添加id='user_input'形式,因此它应该是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);

javascript html web-deployment
1个回答
0
投票

如果要向单选按钮添加说明,则应创建一个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/

© www.soinside.com 2019 - 2024. All rights reserved.