функция удаления не работает во вновь созданном элементе - PullRequest
0 голосов
/ 09 мая 2020

У меня есть функция, которая добавляет элемент в список, и функция, которая удаляет элемент. Когда я добавляю элемент, он отображается правильно, но его нельзя удалить, пока я не обновлю sh страницу. Я использую python 3, flask и javascript, но я не знаю, почему функция удаления не может быть вызвана для вновь созданного элемента. Это соответствующий код:

index. html:

const checkboxes = document.querySelectorAll('.check-completed');
for (let i = 0; i < checkboxes.length; i++) {
    const checkbox = checkboxes[i];
    checkbox.onchange = function(e) {
        console.log('click')
        const newCompleted = e.target.checked;
        const todoId = e.target.dataset['id'];
        fetch('/todos/' + todoId + '/set-completed', {
                method: 'POST',
                body: JSON.stringify({
                    'completed': newCompleted
                }),
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(function() {
                document.getElementById('error').className = 'hidden';
            })
            .catch(function() {
                document.getElementById('error').className = '';
            })
    }
}

const descInput = document.getElementById('description');
document.getElementById('form').onsubmit = function(e) {
    e.preventDefault();
    const desc = descInput.value;
    descInput.value = '';
    fetch('/todos/create', {
            method: 'POST',
            body: JSON.stringify({
                'description': desc,
            }),
            headers: {
                'Content-Type': 'application/json',
            }
        })
        //.then(response => {
        //  return response.json()
        //  data = response.json()
        //})
        .then(response => response.json())
        .then(jsonResponse => {
            const li = document.createElement('li');
            const checkbox = document.createElement('input');
            checkbox.className = 'check-completed';
            checkbox.type = 'checkbox';
            checkbox.setAttribute('data-id', jsonResponse.id);
            li.appendChild(checkbox);

            const text = document.createTextNode(' ' + jsonResponse.description);
            li.appendChild(text);

            const deleteBtn = document.createElement('button');
            deleteBtn.className = 'xbox';
            deleteBtn.setAttribute('data-id', jsonResponse.id);
            deleteBtn.innerHTML = '&cross;';
            li.appendChild(deleteBtn);

            document.getElementById('todos').appendChild(li);
            document.getElementById('error').className = 'hidden';
        })
        .catch(function() {
            console.error('Error occurred');
            document.getElementById('error').className = '';
        })
}

Удалить код

const deletes = document.querySelectorAll('.xbox');
for (let i = 0; i < deletes.length; i++) {
    const btn = deletes[i];
    btn.onclick = function(e) {
        console.log('click')
        const todoId = e.target.dataset['id'];
        fetch('/todos/' + todoId, {
                method: 'DELETE'
            })
            .then(function() {
                const item = e.target.parentElement;
                item.remove();
            })
    }
}

app.py

@app.route('/todos/create', methods=['POST'])
def create_todo():
    error = False
    body = {}
#   description = request.form.get('description', '')
#   return render_template('index.html')
    try:
        description = request.get_json()['description']
        todo = Todo(description=description)
        #body['description'] = todo.description
        db.session.add(todo)
        db.session.commit()
        body['id'] = todo.id
        body['completed'] = todo.completed
        body['description'] = todo.description
    except:
        error=True
        db.session.rollback()
        print(sys.exc_info())
    finally:
        db.session.close()
    if error:
        abort (400)
    else:
        return jsonify(body)

1 Ответ

0 голосов
/ 09 мая 2020

Я понял. Мне пришлось назвать функции обновления и удаления и вызвать их внутри функции добавления элемента, чтобы присоединить функции к новым элементам css.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...