使用jQuery append方法追加元素时无法应用CSS样式的问题求助
Hey there! I see the issue you're running into—your CSS styles aren't sticking to the tasks you append with jQuery. Let's break down what's going wrong and fix it quickly.
The root cause is how you're using jQuery's append() method. Right now, you're passing multiple separate strings to append():
$("#notCompleted").append('<div class="tasks" id="' + taskNumber + '">', '<input type="checkbox">', '<label>' + d + '</label>', '</div>');
When you pass multiple arguments to append(), jQuery treats each one as a sibling element to insert, not nested content. So your generated HTML ends up looking like this:
<div id="notCompleted"> <!-- existing content --> <div class="tasks" id="0"></div> <!-- Empty .tasks div --> <input type="checkbox"> <!-- Sibling, not inside .tasks --> <label>Your new task</label> <!-- Sibling, not inside .tasks --> </div>
Since the input and label aren't inside the .tasks div, your CSS styles for .tasks don't affect them—making it look like the styles aren't working at all.
Fix 1: Combine all HTML into a single string
Wrap your entire task structure into one string so append() inserts it as a single nested element:
var taskNumber = 0; function insertTask(d) { if ($("#plainText").val() != '') { // Combine the full task HTML into one string var taskHtml = '<div class="tasks" id="' + taskNumber + '">' + '<input type="checkbox">' + '<label>' + d + '</label>' + '</div>'; $("#notCompleted").append(taskHtml); $("#plainText").val(''); taskNumber++; console.log(taskNumber); console.log(d); } }
Fix 2: Use jQuery's element creation (cleaner approach)
For more readable and maintainable code, create elements with jQuery and nest them properly:
var taskNumber = 0; function insertTask(d) { if ($("#plainText").val() != '') { // Create the .tasks div with attributes var taskDiv = $('<div>', { class: 'tasks', id: taskNumber }); // Add checkbox and label inside the div taskDiv.append('<input type="checkbox">'); taskDiv.append('<label>' + d + '</label>'); // Append the complete task block to your container $("#notCompleted").append(taskDiv); $("#plainText").val(''); taskNumber++; console.log(taskNumber); console.log(d); } }
Either way, your new .tasks div will now contain the checkbox and label, so your CSS styles (margin, border-radius, background color) will apply correctly to the entire task block.
内容的提问来源于stack exchange,提问作者Akshay Purohit

