You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用jQuery append方法追加元素时无法应用CSS样式的问题求助

Why Your CSS Isn't Applying to Newly Appended jQuery Elements

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 17:37:38