0

Кто-то может понять в чем причина, счётчик лайков не работает, но в консоли нормально все показывает

const input = document.querySelector('.input')
const btn = document.querySelector('.btn')
const test = document.querySelector('.test')
let counter = document.querySelector('.counter')

const addPost = () => {
  counter = 0;
  const markup = 
  `<div class="test-wrapper">
      <div class="test-message">
         <img src="img/images.png" alt="">
         <h3 class="message-text">${input.value}</h3>
        </div>
        <div class="test-like">
         <svg height="20px" style="enable-background:new 0 0 512 512;" version="1.1" viewBox="0 0 512 512" width="20px" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
          <g id="_x31_66_x2C__Heart_x2C__Love_x2C__Like_x2C__Twitter">
       <g>
                <path d="M365.4,59.628c60.56,0,109.6,49.03,109.6,109.47c0,109.47-109.6,171.8-219.06,281.271    C146.47,340.898,37,278.568,37,169.099c0-60.44,49.04-109.47,109.47-109.47c54.73,0,82.1,27.37,109.47,82.1    C283.3,86.999,310.67,59.628,365.4,59.628z";/>
       </g>
            </g>
            <g id="Layer_1"/>
         </svg>
         <p class="counter">${counter}</p>
        </div>
     </div>`

  test.insertAdjacentHTML('afterbegin', markup)
  const like = document.querySelector('svg')

  like.addEventListener('click', () => {
    addCounter()
  })

  const addCounter = () => {
    counter += 1;
    console.log(counter)
  }
}
btn.addEventListener('click', () => {
  addPost();
})
@import url("https://fonts.googleapis.com/css2?family=Oswald:wght@700&family=Tiro+Tamil&display=swap");
* {
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  list-style-type: none;
  margin: 0;
  padding: 0;
}

a {
  color: inherit;
  text-decoration: none;
}

body {
  font-family: "Oswald", sans-serif;
  font-size: 18px;
}

.container {
  max-width: 1000px;
  padding: 0 15px;
}

.test-wrapper {
  height: 75px;
  width: 500px;
  border: 1px solid #000;
}

.test-message img {
  height: 35px;
  width: 35px;
}

.message-text {
  display: inline-block;
}

svg {
  fill: #eee;
}

svg:hover {
  fill: red;
}

.counter {
  display: inline-block;
  font-size: 14px;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" type="text/css" href="css/style.css">
  <link rel="shortcut icon" type="image/ico" href="img/favicon.ico">
</head>

<body>
  <div class="container">
    <div class="test">

    </div>

    <input class="input" type="text" name="message">
    <button class="btn">click</button>
  </div>

  <script src="js/script.js"></script>
</body>

</html>

1 ответ 1

1

В чём была твоя ошибка, ты пытаешься привязать к псевдо-элементу.

А надо было привязаться к parent, ибо тот-же клик передаться от всех наследников к единому контейнеру.

messagesContainer.addEventListener("click", (event) => {
  const like = event.target.closest(".test-like"); // Выбираем ближайший .test-like из parents
  if (like === null) return; // Если такового нету, значаит клик был не на лайк
  const counter = like.querySelector("P.counter"); // Выбираем ближайший children P.counter
  if (counter !== null) { // Если нету, значит херня какая-то
    counter.dataset.count = parseInt(counter.dataset.count) + 1; // Увеличиваем на 1
    counter.textContent = counter.dataset.count; // Выводим значение
  }
});

Вот рабочий вариант твоего счётчика.

4
  • ps: А ещё дико бесят конструкции const addPost = () => {} Вот скажи чем тебе function addPost() {} не угодил? Тебе что надо передавать где-то this в функцию? Если ты не относишь код к классу то вообще зачем так писать? Это становиться жутко нечитаемо, аш противно.
    – Eugene X
    31 мая 2022 в 19:08
  • Прости, не бей пожалуйста, я в основном так и пишу function и так далее, это просто единичный случай такой 31 мая 2022 в 19:11
  • @АндрейХотюн Ну надеюсь ) Просто shorthands делают код совершенно нечитаемым, честно.
    – Eugene X
    31 мая 2022 в 19:14
  • А если допустим надо убрать лайки, тоесть поставил лайк, передумал и еще раз нажал и убрал, это через условного оператора делать, да? Прописать в likeContainer.addEventListener? 1 июн 2022 в 8:17

Ваш ответ

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

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