jQuery - 使用复选框附加更改 [英] jQuery - append changes using checkboxes

查看:37
本文介绍了jQuery - 使用复选框附加更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不是使用添加按钮将项目添加到列表中,而是使用删除按钮删除附加项目,如何使它们成为相同的按钮(或输入),以便在选中时该项目被附加到列表中,如果它是未选中,它将从列表中删除?

Instead of adding the item to the list using an add button and then removing the appended item using a remove button, how do I make them the same button (or input) so that if it is checked the item is appended to the list and if it is unchecked it is removed from the list?

我需要添加和删除相同的按钮,以便我可以通过取消选中项目按钮或附加项目的按钮来从列表中删除项目。

I need the add and remove to be the same button so that I can remove the item from the list by either unchecking the item button OR the appended item's button.

// 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);
  };

  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);
    addToWish({
      id: product.id,
      img: product.img,
      name: product.name,
    });
  });
  //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>"
      );
      //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);
      };
      (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);
          }, 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>

推荐答案

更新:您可以考虑将 removeFromWish()移至与 addToWish()以便其他函数可以访问它。

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>

这篇关于jQuery - 使用复选框附加更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆