[英]Apply styling to dynamically created checkbox
我有一组从引导程序中获得的复选框,它们看起来更像是按钮而不是复选框,但它们的选中状态仍然会在点击时切换。 我在表单上有一个文本输入,允许用户添加带有与用户输入相对应的标签和值的复选框。 所有的复选框都在同一个div
组件中。
我使用 javascript 动态创建新复选框,并使用 append 将其添加到label
,该复选框被附加到包含复选框的div
中。 新复选框出现在页面上,但没有样式,该样式链接在 html 文档的头部。 如何将样式应用于新复选框?
这是我正在使用的 javascript:
function addRestriction() {
let userInput = document.getElementById("add_other").value; // get user input
let newBox = document.createElement("input");
newBox.type = "checkbox";
newBox.autocomplete = 'off';
newBox.name = 'diet_button';
newBox.value = userInput;
let newLabel = document.createElement("label");
newLabel.class = "btn btn-outline-secondary active";
newLabel.appendChild(newBox);
newLabel.appendChild(document.createTextNode(userInput));
document.getElementById('diet_restrictions').appendChild(newLabel);
document.getElementById('add_other').value = '';
}
两个答案都是正确的:
element.className = "new-class"
将仅将此元素 class 名称设置为“new-class” 而:
element.classList.add("new-class")
将新的 class 添加到现有的类集。 如果您要在新创建的复选框中进一步扩展类,此功能可能很有用。
这个小提琴显示了差异。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.