Как сделать так, чтобы значки добавлялись и добавлялись для изменения внешнего вида - PullRequest
0 голосов
/ 03 мая 2018

Я пытаюсь запустить простую функцию добавления и добавления карт, при которой, когда пользователь нажимает на значки, он сразу переключается на заполненный или другой цветной значок. Однако ссылка родительского div также наследуется, поэтому я добавил stopPropagation в скрипт. Я еще не добавил код html & script для #addtocart, так как функция будет похожа на значок #heart like.

Проблема в том, что переключатель не работает + мой редактор выдает мне сообщение «Ошибка: $ undefined», даже если я правильно связываю свой JavaScript. Я был бы признателен, если кто-то может помочь указать, где я ошибся. В конечном итоге я хотел бы добавить функциональность, посредством которой нажатие на значки добавит продукт в список пожеланий пользователя или на страницу корзины, но мне еще предстоит научиться кодировать бэкэнд, поэтому я пока просто отображаю пользовательский интерфейс. Однако, если вы можете сказать мне, как я могу сделать так, чтобы значки связывались со списком пожеланий пользователя или страницей корзины, а не наследовали ссылку родителя, это было бы здорово.

$(document).ready(function() {
  $('#heart').click(function() {
    $('#heart--liked').toggle('1000');
  });
  $("#heart a").click(function(e) {
    //do something to stop link # from loading
    e.stopPropagation();
  });
});
.product__list__item {
  border-radius: 2px;
  background-color: var(--pure-white);
  border: solid 1px var(--dark-grey);
}

.product__list__item--description {
  padding: 1.5rem;
  text-align: left;
}

.product__list__item h3 {
  margin-bottom: .75rem;
  position: relative;
  display: block;
}

.product__list__item--icons {
  display: inline-block;
  float: left;
  padding-top: 5px;
}

.product__list__item--icons a {
  color: var(--middle-grey);
}

.product__list__item--icons a:hover {
  color: var(--dark-grey);
}

#heart--liked {
  display: none;
  transition: .2s;
}

#addtocart {
  margin-left: 10px;
}

.product__list__item--price {
  display: inline-block;
  float: right;
  color: var(--dark-gray);
  font-size: 1.5rem;
  text-align: right;
  margin-top: 50px;
}

.price--hot {
  color: var(--crimson-red);
}

.price--display {
  color: var(--pompeian-pink);
}

.product__list__item--description h3 sup {
  font-size: .875rem;
  padding: 5px;
  text-transform: uppercase;
  vertical-align: super;
}

.price__sale {
  text-decoration: line-through;
  font-size: 1.25rem;
  color: var(--highlight-gray);
  margin-left: 5px;
  vertical-align: sub;
}

.product__list__item--description:after {
  content: "";
  display: table;
  clear: both;
}
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.11/css/all.css" integrity="sha384-p2jx59pefphTFIpeqCcISO9MdVfIm4pNnsL08A6v5vaQc4owkQqxMV8kg4Yvhaw/" crossorigin="anonymous">


</head>

<body>
  <div class="product__list__item">
    <a href="#" class="image-container">
      <div class="image-container__wrapper">
        <div class="image-container--mask">
          <h4>View details</h4>
        </div>
        <img src="https://foter.com/photos/235/design-tree-home-acapulco-lounge-chair-yellow-1.jpg?s=pi" alt="yellow chair">
      </div>
      <div class="product__list__item--description">
        <h3>Yellow Chair<sup class="price--hot">Clearance!</sup></h3>
        <div class="product__list__item--icons">
          <span id="heart"><a href=" "><i class="far fa-heart fa-2x"></i><i id="heart--liked" class="fas fa-heart fa-2x"></i></a></span>
          <span id="addtocart"><a href=" "><i class="fas fa-cart-plus fa-2x"></i></a></span>
        </div>
        <div class="product__list__item--price price--hot">$189
          <sub class="price__sale">$109</sub>
        </div>
      </div>
    </a>

  </div>

</body>

</html>

Ответы [ 2 ]

0 голосов
/ 03 мая 2018

$ не определено, потому что у вас есть имя в скобках. так что у вас просто много переменных без имени ...

   $document.ready(function() {
      $heart.click(function() {
        $heart-liked.toggle('1000');
      });
      $heart.a.click(function(e) {
        e.stopPropagation();
      });
    });
0 голосов
/ 03 мая 2018

Я предлагаю вам использовать класс для изменения цвета при нажатии.

Смотрите ниже рабочий фрагмент, где я пытался уважать ваш образ действий:
Я добавил CSS-переменные в тело, чтобы он работал, и некоторые комментарии, где я добавил / изменил вещи.

$(document).ready(function() {

  // Specific code for the heart fill toggle
  $("#heart--liked").click(function(e) {
    $(this).toggleClass("far").toggleClass("fas"); // Toggle the filling !
  });

  // Action when click on a link (color)
  $(".product__list__item--icons a").click(function(e) {
    e.preventDefault(); // Modified: stop link # from loading (Why using link then?)
    $(this).toggleClass("selected"); // Toggle the colored class !
  });

});
.product__list__item {
  border-radius: 2px;
  background-color: var(--pure-white);
  border: solid 1px var(--dark-grey);
}

.product__list__item--description {
  padding: 1.5rem;
  text-align: left;
}

.product__list__item h3 {
  margin-bottom: .75rem;
  position: relative;
  display: block;
}

.product__list__item--icons {
  display: inline-block;
  float: left;
  padding-top: 5px;
}

.product__list__item--icons a {
  color: var(--middle-grey);
}

.product__list__item--icons a:hover {
  color: var(--dark-grey);
}


/* Added the two below */

.product__list__item--icons .selected {
  color: var(--light-pink);
}

.product__list__item--icons .selected:hover {
  color: var(--pink);
}

#heart--liked {
  /*display: none; REMOVED */
  transition: .2s;
}

#addtocart {
  margin-left: 10px;
}

.product__list__item--price {
  display: inline-block;
  float: right;
  color: var(--dark-gray);
  font-size: 1.5rem;
  text-align: right;
  margin-top: 50px;
}

.price--hot {
  color: var(--crimson-red);
}

.price--display {
  color: var(--pompeian-pink);
}

.product__list__item--description h3 sup {
  font-size: .875rem;
  padding: 5px;
  text-transform: uppercase;
  vertical-align: super;
}

.price__sale {
  text-decoration: line-through;
  font-size: 1.25rem;
  color: var(--highlight-gray);
  margin-left: 5px;
  vertical-align: sub;
}

.product__list__item--description:after {
  content: "";
  display: table;
  clear: both;
}
<html>

<head>
  <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.11/css/all.css" integrity="sha384-p2jx59pefphTFIpeqCcISO9MdVfIm4pNnsL08A6v5vaQc4owkQqxMV8kg4Yvhaw/" crossorigin="anonymous">
</head>

<body style="--middle-grey: #888; --dark-grey: #444; --light-pink: #ffb6c1; --pink: #dd888b;">
  <div class="product__list__item">
    <a href="#" class="image-container">
      <div class="image-container__wrapper">
        <div class="image-container--mask">
          <h4>View details</h4>
        </div>
        <img src="https://foter.com/photos/235/design-tree-home-acapulco-lounge-chair-yellow-1.jpg?s=pi" alt="yellow chair">
      </div>
      <div class="product__list__item--description">
        <h3>Yellow Chair<sup class="price--hot">Clearance!</sup></h3>
        <div class="product__list__item--icons">
          <span id="heart"><a href=" "><i id="heart--liked" class="far fa-heart fa-2x"></i></a></span>
          <span id="addtocart"><a href=" "><i class="fas fa-cart-plus fa-2x"></i></a></span>
        </div>
        <div class="product__list__item--price price--hot">$189
          <sub class="price__sale">$109</sub>
        </div>
      </div>
    </a>
  </div>
</body>

</html>

Надеюсь, это поможет.

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