2

Помогите сделать кнопку удаления(на фотографиях показан как красный символ "X") Как бы не пробовал, всё равно не так

$(function() {
    var $tasksList = $("#tasksList");
    var $taskImput = $("#taskImput");
    var $notification = $("#notification");
    var $description = $("#description");


    var displayNotification = function() {
        if (!$tasksList.children().length) {
            $list.fadeIn("fast");
        } else{
            $list.css("display", "none")
        }
    }

    $("#add-button").on("click" , function() {
        if (!$taskImput.val()) {return false;}

        $notification.remove();

        $tasksList.append("<div class='note'><div class='name'>" + $taskImput.val() + "<button class='delete'>&#10006</button></div><p class='desc'>" + $description.val() + "</p></div>");
    
        $taskImput.val("");

        $description.val("");

        displayNotification();

        $(".delete").on("click", function(){
            var $parent = $(this).parent().parent();
            $parent.remove();
        });

    });
});
html, body {
  margin: 0;
  padding: 0;
  min-width: 1000px;
  font-family: Arial;
  background-color: #f5f5f5;
}

h2 {
  font-size: 21px;
  font-weight: normal;
}

li {
  list-style-type: none;
}

.fixed-container {
  width: 960px;
  margin: 0 auto;
}

#central-conteiner {
  margin-top: 65px;
}

#to-do-list {
  float: left;
}

#add-case {
  float: right;
}

#menu-adding {
  background-color: #fcfcfc;
  width: 420px;
  height: 500px;
  padding-top: 50px;
  padding-left: 40px;
  color: #8993ad;
  font-size: 14px;
}

#notification {
  margin-top: 80px;
  font-size: 16px;
  color: #8993ad;
}

#taskImput {
  height: 45px;
  width: 372px;
  margin-top: 10px;
  margin-bottom: 30px;
  font-size: 16px;
  padding-left: 14px;
  background-color: #f9f9f9;
  border: 1px solid #ebebeb;
}

#description {
  width: 372px;
  height: 205px;
  padding-left: 14px;
  padding-top: 21px;
  font-size: 16px;
  background-color: #f9f9f9;
  border: 1px solid #ebebeb;
  resize: none;
}

#add-button {
  margin-top: 30px;
  width: 224px;
  height: 55px;
  background-color: #2174fd;
  border: none;
  color: #ffffff;
  font-size: 16px;
}

.note {
  width: 470px;
  height: 135px;
  background-color: #ffffff;
  margin-bottom: 20px;
  margin-left: -40px;
}
  .name {
    font-weight: normal;
    border-bottom: 1px solid #f7f7f7;
    padding-left: 20px;
    padding-bottom: 20px;
    padding-top: 18px;
    margin: 0;
    padding-right: 25px;
    font-size: 16px;
    color: black;
  }

  .desc {
    padding-left: 20px;
    font-size: 14px;
    color: #8993ad;
  }

  .delete {
    margin-left: 50px;
    background-repeat: no-repeat;
    height: 24px;
    width: 36px;
    border: none;
    background-color: #ffffff;
    color: red;
  }
<!DOCTYPE html>
<html lang="ru">
<head>
    <link rel="stylesheet" type="text/css" href="styles.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="script.js"></script>
    <title>Список дел</title>
</head>
<body>
    <div id="central-conteiner">
    <div class="fixed-container">
        <aside id="to-do-list">
            <h2>Список дел</h2>
            <div id="notification">Список пуст...</div>
            <ul id="tasksList"></ul>
        </aside>
        <aside id="add-case">
            <h2>Добавить новое дело</h2>
            <div id="menu-adding">
                * Название<br>
                <input type="text" name="note" id="taskImput"><br>
                * Описание<br>
                <textarea id="description"></textarea><br>
                <button id="add-button">Добавить дело</button>
            </div>
        </aside>
    </div>
    </div>
</body>
</html>

2 ответа 2

1

Ругается консоль на эту переменную $list. Удалять $("#notification") нет необходимости. Можно просто скрывать. А показывать только при проверке на пустой список дел. Вызывать проверку можно при удалении .note В целом функцию displayNotification можно упростить. Также Вы каждый раз вешаете обработчик на все элементы с классом .delete. То есть повторно на уже созданные элементы, это не так критично, но копить их точно не стоит. Поэтому можно назначать ID вашим записям и назначть обработчик на конкретный элемент.

$(function() {
    var $tasksList = $("#tasksList");
    var $taskImput = $("#taskImput");
    var $notification = $("#notification");
    var $description = $("#description");


    var displayNotification = function() {
        if ($('.note').length == 0) {
          $notification.fadeIn("fast");
        }        
    }
    
    const getId = () => {      
      return ($('.note').length == 0) ? 1 : +$('.note').last().attr('id') + 1;
    }

    $("#add-button").on("click" , function() {
        if (!$taskImput.val()) {return false;}        
        $notification.hide();        
        let id = getId();
        $tasksList.append("<div id="+id+" class='note'><div class='name'>" + $taskImput.val() + "<button class='delete'>&#10006</button></div><p class='desc'>" + $description.val() + "</p></div>");
    
        $taskImput.val("");
        $description.val("");        

        $(`#${id} .delete`).on("click", function(){            
          $(`#${id}`).remove();
          displayNotification();
        });

    });
});

$(function() {
    var $tasksList = $("#tasksList");
    var $taskImput = $("#taskImput");
    var $notification = $("#notification");
    var $description = $("#description");


    var displayNotification = function() {
        if ($('.note').length == 0) {
          $notification.fadeIn("fast");
        }        
    }
    
    const getId = () => {      
      return ($('.note').length == 0) ? 1 : +$('.note').last().attr('id') + 1;
    }

    $("#add-button").on("click" , function() {
        if (!$taskImput.val()) {return false;}        
        $notification.hide();        
        let id = getId();
        $tasksList.append("<div id="+id+" class='note'><div class='name'>" + $taskImput.val() + "<button class='delete'>&#10006</button></div><p class='desc'>" + $description.val() + "</p></div>");
    
        $taskImput.val("");
        $description.val("");        

        $(`#${id} .delete`).on("click", function(){            
          $(`#${id}`).remove();
          displayNotification();
        });

    });
});
html, body {
  margin: 0;
  padding: 0;
  min-width: 1000px;
  font-family: Arial;
  background-color: #f5f5f5;
}

h2 {
  font-size: 21px;
  font-weight: normal;
}

li {
  list-style-type: none;
}

.fixed-container {
  width: 960px;
  margin: 0 auto;
}

#central-conteiner {
  margin-top: 65px;
}

#to-do-list {
  float: left;
}

#add-case {
  float: right;
}

#menu-adding {
  background-color: #fcfcfc;
  width: 420px;
  height: 500px;
  padding-top: 50px;
  padding-left: 40px;
  color: #8993ad;
  font-size: 14px;
}

#notification {
  margin-top: 80px;
  font-size: 16px;
  color: #8993ad;
}

#taskImput {
  height: 45px;
  width: 372px;
  margin-top: 10px;
  margin-bottom: 30px;
  font-size: 16px;
  padding-left: 14px;
  background-color: #f9f9f9;
  border: 1px solid #ebebeb;
}

#description {
  width: 372px;
  height: 205px;
  padding-left: 14px;
  padding-top: 21px;
  font-size: 16px;
  background-color: #f9f9f9;
  border: 1px solid #ebebeb;
  resize: none;
}

#add-button {
  margin-top: 30px;
  width: 224px;
  height: 55px;
  background-color: #2174fd;
  border: none;
  color: #ffffff;
  font-size: 16px;
}

.note {
  width: 470px;
  height: 135px;
  background-color: #ffffff;
  margin-bottom: 20px;
  margin-left: -40px;
}
  .name {
    font-weight: normal;
    border-bottom: 1px solid #f7f7f7;
    padding-left: 20px;
    padding-bottom: 20px;
    padding-top: 18px;
    margin: 0;
    padding-right: 25px;
    font-size: 16px;
    color: black;
  }

  .desc {
    padding-left: 20px;
    font-size: 14px;
    color: #8993ad;
  }

  .delete {
    margin-left: 50px;
    background-repeat: no-repeat;
    height: 24px;
    width: 36px;
    border: none;
    background-color: #ffffff;
    color: red;
    cursor: pointer;
  }
<!DOCTYPE html>
<html lang="ru">
<head>
    <link rel="stylesheet" type="text/css" href="styles.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="script.js"></script>
    <title>Список дел</title>
</head>
<body>
    <div id="central-conteiner">
    <div class="fixed-container">
        <aside id="to-do-list">
            <h2>Список дел</h2>
            <div id="notification">Список пуст...</div>
            <ul id="tasksList"></ul>
        </aside>
        <aside id="add-case">
            <h2>Добавить новое дело</h2>
            <div id="menu-adding">
                * Название<br>
                <input type="text" name="note" id="taskImput"><br>
                * Описание<br>
                <textarea id="description"></textarea><br>
                <button id="add-button">Добавить дело</button>
            </div>
        </aside>
    </div>
    </div>
</body>
</html>

0

В вашем коде несколько ошибок.

  1. В $('#to-do-list').append(...), вы пытаетесь добавить что-то в элемент, который не существует. Вместо #to-do-list, должно быть #list.

  2. $('#name') и $('#note-text') идентифицируют элементы по их id. В вашем случае, вы хотите их идентифицировать по class, поэтому используйте $('#list .note:last .name').

  3. Линия $('#list').remove(); стирает всё в списке. Не думаю, что это то, что вы хотите. Используйте флаг (переменную true/false) которая будет определять, есть ли что-то в списке. Или пишите вот так:

    <div id="list">
        <div id="empty">Список пуст...</div>
    </div>
    
    $('#empty').remove();
    

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.