[英]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.