RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 1243007
Accepted
Wells
Wells
Asked:2022-02-12 05:03:34 +0000 UTC2022-02-12 05:03:34 +0000 UTC 2022-02-12 05:03:34 +0000 UTC

JS 脚本有什么区别(onClick & addEventListener)

  • 772

为了练习,我正在编写一个 Todo 应用程序,但不可能编写一个脚本。在网上找到了现成的解决方案——通过onClick来实现,而不是addEventListener。

'use strict';

const input = document.querySelector('.todo-input');
let count = 0,
    todoAmount = 0;

document.querySelector('.items-left').textContent = `${todoAmount} items left`;

class TodoConstructor {
    constructor(input, parentSelector) {
        this.value = input.value;
        this.parent = document.querySelector(parentSelector);
    }

    
    render() {
        if (document.querySelector('.text-container')) {
            document.querySelector('.text-container').style.display = 'none';
        }
        
        const newTodo = document.createElement('div');
        newTodo.classList.add('new-todo-container', 'new-container');

        newTodo.innerHTML = `
            <div class="checkbox-wrapper">
                <input type="checkbox" id="new-todo-${todoAmount}"  name="inputs" class="custom-checkbox">
                <label for="new-todo-${todoAmount}">
                <svg xmlns="http://www.w3.org/2000/svg" width="11" height="9">
                    <path fill="none" stroke="#FFF" stroke-width="2" d="M1 4.304L3.696 7l6-6"/>
                <svg>
                </label>
            </div>
            <span class="todo-text">${this.value}</span>
            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" class="close close-enable"><path d="M16.97 0l.708.707L9.546 8.84l8.132 8.132-.707.707-8.132-8.132-8.132 8.132L0 16.97l8.132-8.132L0 .707.707 0 8.84 8.132 16.971 0z"/></svg>
        `;
        this.parent.prepend(newTodo);
        countAllTodos();
        
        
    }
}

function checkEmptyInput() {
    input.addEventListener('input', () => {
        if (input.value == '') {
            document.querySelector('.new-todo-container').style.border = '1px solid red';
        } else {
            document.querySelector('.new-todo-container').style.border = '1px solid hsl(0, 0%, 90%)';
        }
    });
}

function checkForEmptyContent() {
    const contentContainer = document.querySelector('.content-container');
    contentContainer.addEventListener('click', () => {
        if (!document.querySelectorAll('.close-enable').length) {
            document.querySelector('.text-container').style.display = 'flex';
        } 
    });
}

function createNewTodo() {
    input.addEventListener('keydown', (e) => {
        if (e.code === "Enter" && input.value !== '') { 
            ++todoAmount;
            console.log(todoAmount);
            new TodoConstructor(input, '.content-container').render();
            input.value = '';
            checkForEmptyContent();
            deleteBtnClick();
            // bindTodoDelete();
        }
    });
}

// Первый способ - неправильно считает общее кол-во задач
function bindTodoDelete() {
    const deleteBtns = document.querySelectorAll('.close-enable');
    --todoAmount;
    for (let i = 0; 0 < deleteBtns.length; i++) {
        deleteBtns[i].addEventListener('click', (e) => {
            if (e.target.tagName == 'svg') {
                e.target.parentElement.remove();
            } else {
                const parent = e.target.parentElement;
                parent.parentElement.remove();
            }
        });
        countAllTodos();
    }
    
}

// Второй способ - правильно считает кол-во задач
function deleteBtnClick(){
    const deleteBtns = document.getElementsByClassName("close-enable");
    var j;
    for( j = 0; j < deleteBtns.length; j++){
        deleteBtns[j].onclick = function() {
            const parent = this.parentElement;
            parent.remove();
            --todoAmount;
            countAllTodos();
        }; 
    }
}

function countAllTodos() {
    document.querySelector('.items-left').textContent = `${todoAmount} items left`;
}



createNewTodo();
checkEmptyInput();
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- displays site properly based on user's device -->

  <link rel="icon" type="image/png" sizes="32x32" href="./images/favicon-32x32.png">
  <link rel="preconnect" href="https://fonts.gstatic.com">
  <link href="https://fonts.googleapis.com/css2?family=Josefin+Sans:wght@400;700&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="styles.css">
  <title>Frontend Mentor | Todo app</title>

  <!-- Feel free to remove these styles or customise in your own stylesheet 👍 -->
  <style>
    

  </style>
</head>
<body>
  <div class="button" id="btn">click me</div>
  <div class="button" id="btnn">click me tool</div>
  <div class="main-container">
    <div class="header-container">
      <h1 class="header">todo</h1>
      <div class="change-theme"><svg xmlns="http://www.w3.org/2000/svg" width="26" height="26"><path fill="#FFF" fill-rule="evenodd" d="M13 0c.81 0 1.603.074 2.373.216C10.593 1.199 7 5.43 7 10.5 7 16.299 11.701 21 17.5 21c2.996 0 5.7-1.255 7.613-3.268C23.22 22.572 18.51 26 13 26 5.82 26 0 20.18 0 13S5.82 0 13 0z"/></svg></div>
    </div>
    <div class="new-todo-container input-container">
        <div class="checkbox-wrapper">
          <input type="checkbox" id="new-todo-checkbox"  name="inputs" class="custom-checkbox">
          <label for="new-todo-checkbox"><svg xmlns="http://www.w3.org/2000/svg" width="11" height="9"><path fill="none" stroke="#FFF" stroke-width="2" d="M1 4.304L3.696 7l6-6"/></svg></label>
        </div>
        <input class="todo-input" type="text" id="new-todo-text" name="inputs" placeholder="Create a new todo...">
    </div>
    <div class="content-container">
      <div class="new-todo-container text-container">
        <div class="checkbox-wrapper">
          <input type="checkbox" id="new-todo-ex"  name="inputs" class="custom-checkbox" disabled>
          <label for="new-todo-ex">
            <svg xmlns="http://www.w3.org/2000/svg" width="11" height="9">
              <path fill="none" stroke="#FFF" stroke-width="2" d="M1 4.304L3.696 7l6-6">
              </svg>
          </label>
        </div>
        <span class="todo-text unselectable">Here your todo will be displayed</span>
        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" class="close close-disabled"><path d="M16.97 0l.708.707L9.546 8.84l8.132 8.132-.707.707-8.132-8.132-8.132 8.132L0 16.97l8.132-8.132L0 .707.707 0 8.84 8.132 16.971 0z"/></svg>
      </div>
      <div class="footer-container">
        <div><span class="items-left"></span></div>
        <ul class="footer-states">
          <li class="footer-item all-items">All</li>
          <li class="footer-item items-active">Active</li>
          <li class="footer-item items-completed">Completed</li>
        </ul>
        <div class="clear-btn-wrapper">
          <button class="footer-item clear-btn">Clear Completed</button>
        </div>
      </div>
    </div>
  </div>
  <div class="attribution">
    Challenge by <a href="https://www.frontendmentor.io?ref=challenge" target="_blank">Frontend Mentor</a>. 
    Coded by <a href="#">Your Name Here</a>.
  </div>
  <script src="script.js"></script>
</body>
</html>

我不知道我需要哪一段代码,所以我粘贴了所有的 JS 和 HTML。我不明白的主要问题是:

  • 为什么第一个bindTodoDelete函数在从页面删除任务时,会错误计算剩余任务总数,但同时第二个deleteBtnClick工作正常。我认为这是因为 forEach 方法,但我无法完全理解我的错误在哪里。如果需要添加更多内容,我一定会更新问题。如果对代码有其他的编辑和评论,那么我会很乐意倾听。谢谢!
javascript
  • 1 1 个回答
  • 10 Views

1 个回答

  • Voted
  1. Best Answer
    Юрий Копоть
    2022-02-12T05:24:54Z2022-02-12T05:24:54Z

    在函数中bindTodoDelete- 立即调用时,有一个递减--todoAmount;。一旦你调用函数,bindTodoDelete变量todoAmount立即减1(虽然从代码来看,这不是必须的)。并且变量本身没有onClick工作todoAmount

    在函数中deleteBtnClick- 有一个事件的初始化click。并且已经在活动click中,对变量的处理正在进行中todoAmount

    addEventListener所以在这种情况下和之间没有区别onclick。只是变量的减量调用在错误的地方。

    • 1

相关问题

  • 第二个 Instagram 按钮的 CSS 属性

  • 由于模糊,内容不可见

  • 弹出队列。消息显示不正确

  • 是否可以在 for 循环中插入提示?

  • 如何将 JSON 请求中的信息输出到数据表 Vuetify vue.js?

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    表格填充不起作用

    • 2 个回答
  • Marko Smith

    提示 50/50,有两个,其中一个是正确的

    • 1 个回答
  • Marko Smith

    在 PyQt5 中停止进程

    • 1 个回答
  • Marko Smith

    我的脚本不工作

    • 1 个回答
  • Marko Smith

    在文本文件中写入和读取列表

    • 2 个回答
  • Marko Smith

    如何像屏幕截图中那样并排排列这些块?

    • 1 个回答
  • Marko Smith

    确定文本文件中每一行的字符数

    • 2 个回答
  • Marko Smith

    将接口对象传递给 JAVA 构造函数

    • 1 个回答
  • Marko Smith

    正确更新数据库中的数据

    • 1 个回答
  • Marko Smith

    Python解析不是css

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5