且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery - 使用复选框附加更改

更新时间:2023-10-15 08:45:46

更新:您可以考虑将 removeFromWish()移至与 addToWish()$相同的范围内c $ c>以便其他函数可以访问它。

Update: You may consider moving removeFromWish() to the same scope as addToWish() so that it is accessible to other functions.

您可以使用jquery查看是否选中了复选框,然后附加项目或从中删除项目相应的列表。

You can use jquery to see if the checkbox is checked, then either append the item or remove the item from the list accordingly.

$(".my-wish-add").on("change", function() {
  var product = getProductValues(this);
  if ($(this).is(":checked")) {
    addToWish({
      id: product.id,
      img: product.img,
      name: product.name,
    });
  } else {
    removeFromWish(product.id);
  }
});

进行这两项更改应该可以解决您的问题。如果要在删除列表项时取消选中该复选框,您还可以尝试以下操作:

Making these two changes should be able to solve your problem. If you want to uncheck the checkbox upon removal of the list item, you can also try the following:

(function() {
    var currentIndex = i;
    $("#my-wish-remove" + currentIndex).on("change", function() {
      $(this)
        .closest("li")
        .hide(400);
      setTimeout(function() {
        wish.items[currentIndex].stock = "";
        update_product(wish.items[currentIndex]);
        removeFromWish(wish.items[currentIndex].id);
        // uncheck (productID - 1)th checkbox
        $(".my-wish-add").eq(wish.items[currentIndex].id - 1).prop("checked", false);
      }, 400);
    });
  })();

取消选中此类复选框可能不太清楚。我希望你能得到基本的想法并调整这些代码,使其符合你的风格。

Unchecking a checkbox like this may not be very clear. I hope you get the basic idea and adapt this code so that it fits your style.

[更新] 演示:

// Wish Function
var wish = {
  items: []
};
var update_product = function(product) {};
$(function() {
  //Add to wish
  var addToWish = function(product, qty) {
    qty = qty || 1;
    var wish = getWish();
    var indexOfId = wish.items.findIndex(x => x.id == product.id);
    if (indexOfId === -1) {
      wish.items.push({
        id: product.id,
        img: product.img,
        name: product.name,
      });
      $parent = $("#" + product.id).closest(".items__wish");
      $parent
        .find(".wish-icon")
        .addClass("active")
        .attr("data-prefix", "fas");
    } else {
      wish.items[indexOfId].qty++;
      wish.items[indexOfId].stock = Number(product.stock);
    }
    //Update popup wish
    updateWish(wish);
  };

  //Remove from wish on id
  var removeFromWish = function(id) {
    var wish = getWish();
    var wishIndex = wish.items.findIndex(x => x.id == id);
    wish.items.splice(wishIndex, 1);
    $parent = $("#" + id).closest(".items__wish");
    $parent
      .find(".wish-icon")
      .first()
      .removeClass("active")
      .attr("data-prefix", "far");
    //Update popup wish
    updateWish(wish);
  };

  var getProductValues = function(element) {
    var productId = $(element)
      .closest(".items__wish")
      .find(".item__tile")
      .attr("id");
    var productImg = $(element)
      .closest(".items__wish")
      .find(".item__img")
      .attr("src");
    var productName = $(element)
      .closest(".items__wish")
      .find(".item__title")
      .html();
    return {
      id: productId,
      img: productImg,
      name: productName,
    };
  };

  $(".my-wish-add").on("change", function() {
    var product = getProductValues(this);
    if ($(this).is(":checked")) {
      addToWish({
        id: product.id,
        img: product.img,
        name: product.name,
      });
    } else {
      removeFromWish(product.id);
    }
  });

  //Update wish html to reflect changes
  var updateWish = function(wish) {
    //Add to shopping wish dropdown
    $(".wishlist__items").html("");
    for (var i = 0; i < wish.items.length; i++) {
      $(".wishlist__items").append(
        "<li>" +
        '<div class="my-wish-item">' +
        "<img src='" +
        wish.items[i].img +
        "' />" +
        '<div class="wish-main">' +
        '<div class="wish-name">' +
        wish.items[i].name +
        "</div>" +
        '<div class="my-wish-remove-container">' +
        '<input type="checkbox" id="my-wish-remove' +
        i +
        '" class="my-wish-remove" aria-hidden="true">' +
        "<i class='fas fa-heart'></i>" +
        "</div>"
      );

      (function() {
        var currentIndex = i;
        $("#my-wish-remove" + currentIndex).on("change", function() {
          $(this)
            .closest("li")
            .hide(400);
          setTimeout(function() {
            wish.items[currentIndex].stock = "";
            update_product(wish.items[currentIndex]);
            $(".my-wish-add").eq(wish.items[currentIndex].id - 1).prop("checked", false);
            removeFromWish(wish.items[currentIndex].id);
          }, 400);
        });
      })();
    }
  };
  //Get Wish
  var getWish = function() {
    var myWish = wish;
    return myWish;
  };
});

body {
  font-family: "Font Awesome\ 5 Pro";
  font-weight: 900;
}

img {
  width: 50px;
}

.wishlist__list {
  position: absolute;
  right: 0;
}

.wishlist__items li {
  list-style: none;
}

<script src="https://pro.fontawesome.com/releases/v5.3.1/js/all.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-id="wishlist">
  <div class="wishlist__list">
    <ul class="wishlist__items">
    </ul>
  </div>
</div>
<div class='products'>
  <div class="items__wish">
    <div id='1' class='item__title item__tile'>Product 1</div>
    <img class="item__img" src="https://www.iconasys.com/wp-content/uploads/2017/06/360-Product-Photography-White-Background-Acrylic-Riser-08.jpg">
    <label class="wish-btn">
    <input type="checkbox" name="wish-check" class='my-wish-add'><i class="wish-icon far fa-heart"></i></input></label>
  </div>
  <div class="items__wish">
    <div id='2' class='item__title item__tile'>Product 2</div>
    <img class="item__img" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQoqpSgkG4AQDQOe33jI1NiW3GW2JSB-_v36aREsVyFQH55JFOJ">
    <label class="wish-btn">
    <input type="checkbox" name="wish-check" class='my-wish-add'><i class="wish-icon far fa-heart"></i></input></label>