简体   繁体   中英

event.target in function doesn't give expected result

I decided to make a to-do list in JavaScript duplicating what is shown in a video but the video is already two years, so that may be some of the properties or something else changed and was deprecated, really I don't know. Here is HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>To-Do list</title>
    <link rel="stylesheet" href="main.css">
</head>
<body>
    <input type="text" id="input">
    <button id="btn">Add</button>

    <hr>

    <ul id="todo">

    </ul>
    <ul id="done">

    </ul>
           
    <script src="main.js"></script>
</body>
</html>

Here is JavaScript:

(function() {
    let input = document.getElementById('input');
    let btn = document.getElementById('btn');
    let lists = {
        todo: document.getElementById('todo'),
        done: document.getElementById('done')
    };

    let makeTaskHtml = function(str, onCheck) {
        let el = document.createElement('li');
        let checkbox = document.createElement('input');
        let label = document.createElement('span');

        checkbox.type = 'checkbox';
        checkbox.addEventListener('click', onCheck);
        label.textContent = str;

        el.appendChild(checkbox);
        el.appendChild(label);

        return el;
    };


    let addTask = function(list, task) {
        list.appendChild(task);
    };

    let onCheck = function(event) {
        let task = event.target;

        console.log(task);
    };

    addTask(lists.todo, makeTaskHtml('Test-todo'));
    addTask(lists.done, makeTaskHtml('Test-done'));


}());

In the function onCheck I tried to console.log task which I defined in this function before but nothing happened: neither errors nor result I expected to see What's the problem? May be it is because of event.target or addEventListener? Help me please to reveal it.

You function makeTaskHtml takes 2 arguments:

function makeTaskHtml(str, onCheck)

But you are only calling it with one:

addTask(lists.todo, makeTaskHtml('Test-todo'));

You need to pass in onCheck as the second argument or remove the second argument from the function declaration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM