【发布时间】:2021-06-03 07:17:11
【问题描述】:
我有一组从引导程序中获得的复选框,它们看起来更像是按钮而不是复选框,但它们的选中状态仍然会在点击时切换。我在表单上有一个文本输入,允许用户添加带有与用户输入相对应的标签和值的复选框。所有的复选框都在同一个div 组件中。
我使用 javascript 动态创建新的复选框并将其附加到 label,该 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 = '';
}
【问题讨论】:
-
尝试 newLabel.className="btn btn-outline-secondary active";
-
添加带有类的新元素将立即应用所有 CSS。您确定类名、元素层次结构和 CSS 规则正确匹配吗?使用 F12 开发工具找出答案。如果你在页面上静态地有这些复选框怎么办?仍然没有应用样式?还有其他使用这些样式的元素吗?
-
element.class 使用 className 或 classList.add() 是错误的
-
newLabel.class = "btn btn-outline-secondary active";==> 改为newLabel.className = "btn btn-outline-secondary active";或newLabel.classList.add("btn", "btn-outline-secondary", "active");
标签: javascript html css checkbox