javascript 编辑我的输入后,赋值id函数不起作用

kiayqfof  于 12个月前  发布在  Java
关注(0)|答案(1)|浏览(104)

我有一个todolist JavaScript代码,编辑我的任务输入后,我的复选框功能,这是分配一个id是线通过不工作。当我选中复选框时,它可以正确地通过我的任务。

addNewTask.addEventListener('click', addTask);

function addTask(e) {

    const li = document.createElement("li");
    li.className = "list-group-item";
    tasks.appendChild(li);

    const label = document.createElement("label");
    label.className = "form-check-label";
    label.innerText = addInput.value;
    label.type = "text";
    label.setAttribute("readonly", "readonly");
    li.appendChild(label);

    const checkBox = document.createElement("input")
    checkBox.className = "form-check-input me-1 fa-pull-right"
    checkBox.type = "checkbox"
    checkBox.name = "chk"
    li.appendChild(checkBox);
    checkBox.id = "checkBox";

    const i2=document.createElement("i");
    i2.className="fa-regular fa-pen-to-square fa-pull-right";
    i2.id="editIcon"
    li.appendChild(i2);
    
    checkBox.addEventListener("change",checkedEvent);
    i2.addEventListener("click",editInput);

}

function editInput(e) {
    if (e.target.classList.contains("fa-pen-to-square")) {
        editIcon.className = "fa-solid fa-floppy-disk fa-pull-right";
        const label = li.firstElementChild;
        const input = document.createElement('input');
        input.type = 'text';
        input.value = label.textContent;
        li.insertBefore(input, label);
        li.removeChild(label);
    } else if (e.target.classList.contains("fa-floppy-disk")) {
        const input = li.firstElementChild;
        const label = document.createElement('label');
        label.className = "form-check-label";
        label.textContent = input.value;
        li.insertBefore(label, input);
        li.removeChild(input);
        editIcon.className = "fa-regular fa-pen-to-square fa-pull-right";
    }
}

function checkedEvent() {

    if (checkBox.checked == true && label.className == "form-check-label") {
        label.id = ("id", "completed");
    } else {
        label.id = ("");
    }
}
#completed{
  opacity: 0.5;
  text-decoration: line-through;
}
<button class="btn btn-primary" type="button" id="addNewTask" >Add new task</button>

我认为我在editInput函数中的新标签元素看起来不像我在addTask函数中创建的旧标签元素。

lymnna71

lymnna711#

是否有多个li带有“items”ID?如果函数正在查找特定的ID,而ID不是唯一的,则可能会遇到问题。
相关链接:https://html.spec.whatwg.org/multipage/dom.html#the-id-attribute

相关问题