JavaScript 创建单选按钮和标签

JavaScript creating a radio button and a label

我正在尝试使用 JavaScript 创建一个单选按钮和一个标签,并且我让单选按钮正常工作,但标签没有出现在它旁边,我不知道我是什么做错了。这是我的代码:


        const x = document.createElement("INPUT");
        x.setAttribute("type", "radio");
        document.body.appendChild(x);


        const y = document.createElement("LABEL");
        const t = document.createTextNode("Label text");
        y.textContent = "Label text";
        y.setAttribute("for", "lord");
        y.appendChild(t);

您需要将标签附加到正文,但您的代码将其附加为单选按钮的子项

const x = document.createElement("INPUT");
x.setAttribute("type", "radio");
x.setAttribute("id", "lord");
document.body.appendChild(x);


const y = document.createElement("LABEL");
const t = document.createTextNode("Label text");
y.textContent = "Label text";
y.setAttribute("for", "lord");
document.body.appendChild(t);

你必须附加到文档,例如单选按钮

document.body.appendChild(y);