代码之家  ›  专栏  ›  技术社区  ›  Petar

完成一个项目会添加两行新行,而函数本身却没有这样的内容

  •  0
  • Petar  · 技术社区  · 8 年前

    在我看过一个教程之后,我自己重新创建了一个todo列表,所有的事情都很好,至少99%是这样。只有一个小问题,没有任何协议中断,但它让我很困扰,因为我无法在函数中找到问题的根源,即使我已经使用调试器缩小了范围问题本身是,每当我在todo列表中将一个项标记为“completed”时,它都会向它添加两个新的空行(就像有人确实单击了Enter x2,这就是它在控制台日志中的显示方式)这个问题发生在“每个项目”上,所以它不像我将一个项目标记为已完成,而是将两个新行添加到每个项目上,而只是添加到正在标记/未标记的项目上下面是一段代码,其中包含了我应该将其缩小到的函数:

    function completeItem(){
        const item = this.parentNode.parentNode;
        const parent = item.parentNode;
        const id = parent.id;
        const value = item.innerText;
    
        if(id === "todo"){
            data.todo.splice(data.todo.indexOf(value), 1)
            data.completed.push(value);
    
            // Notification.
            notification.innerHTML = "<p>Task completed.</p>";
            notification.classList.add("notification");
            notification.classList.add("notificationCompleted");
            setTimeout(() => {
                notification.classList.remove("notification");
                notification.classList.remove("notificationCompleted");
                notification.innerHTML = "";
            }, 2000);
        } else {
            data.completed.splice(data.completed.indexOf(value), 1);
            data.todo.push(value);
        }
        dataObjectUpdate();
        console.log(data);
    
        const target = (id === "todo") ? document.getElementById("completed"):document.getElementById("todo");
    
        parent.removeChild(item);
        target.insertBefore(item, target.childNodes[0]);
    }
    

    如果需要,这里还有到hastebin上整个脚本文件的链接: https://hastebin.com/kuwomiqazu.cs . 这里有一个指向代码笔的链接,显示了该问题: https://codepen.io/pecko95/pen/XBpoGr 提前谢谢。

    2 回复  |  直到 7 年前
        1
  •  1
  •   David Thomas    8 年前

    text content返回所有元素的文本内容,而innerText 返回所有元素的内容,除了 <script> 和 <style> 元素。

    如果你使用文本内容的错误将被修复。

        2
  •  0
  •   Waqar Ul Aziz    8 年前

    替换

    const value = item.innerText;
    

    具有

    const value = item.textContent;