【问题标题】:Apply styling to dynamically created checkbox将样式应用于动态创建的复选框
【发布时间】: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


【解决方案1】:

两个答案都是正确的:

element.className = "new-class"

将只将此元素的类名设置为“new-class” 而:

element.classList.add("new-class")

将向现有的一组类添加一个新类。如果您要在新创建的复选框中进一步扩展类,此功能可能很有用。

This fiddle 显示差异。

  1. .className ref
  2. .classList ref

【讨论】:

  • 谢谢!这行得通。有点奇怪,用于设置类属性的字段不仅仅是类,而是哦。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-07
  • 1970-01-01
  • 2013-01-25
  • 1970-01-01
相关资源
最近更新 更多