简体   繁体   English

将样式应用于动态创建的复选框

[英]Apply styling to dynamically created checkbox

I have a collection of checkboxes which I got from bootstrap that appear more as buttons than checkboxes, but their checked status still toggles on clicks.我有一组从引导程序中获得的复选框,它们看起来更像是按钮而不是复选框,但它们的选中状态仍然会在点击时切换。 I have a text input on the form that allows the user to add checkboxes with labels and values corresponding to the user input.我在表单上有一个文本输入,允许用户添加带有与用户输入相对应的标签和值的复选框。 All of the checkboxes are in the same div component.所有的复选框都在同一个div组件中。

I use javascript to dynamically create the new checkbox and append it to a label , which gets appended to the div containing the checkboxes.我使用 javascript 动态创建新复选框,并使用 append 将其添加到label ,该复选框被附加到包含复选框的div中。 The new checkbox appears on the page, but without the styling, which is linked in the head of the html document.新复选框出现在页面上,但没有样式,该样式链接在 html 文档的头部。 How can I apply the styling to the new checkbox?如何将样式应用于新复选框?

Here is the javascript that I am using:这是我正在使用的 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 = '';
            }

Both answers are correct:两个答案都是正确的:

element.className = "new-class"

Will set this elements only class name to "new-class" While:将仅将此元素 class 名称设置为“new-class” 而:

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

Will add a new class to already existing set of classes.将新的 class 添加到现有的类集。 This feature might be useful in case you are going to further expand classes in your newly created checkboxes.如果您要在新创建的复选框中进一步扩展类,此功能可能很有用。

This fiddle shows the differences.这个小提琴显示了差异。

  1. .className ref .className 参考
  2. .classList ref .classList 参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM