jQuery-对索引函数使用唯一的id

时间:2018-10-26 06:21:33

标签: javascript jquery

在为每个项目使用唯一的remove添加了wishlist中的项目之后,我该如何id?当前代码使用数字索引i删除了该项目,但是我想通过调用唯一的标识符ex(例如:on.change而不是id="dog"来运行下面的id="1", 2, 3函数,依此类推

变量:

for (var i = 0; i < wish.items.length; i++)

有关功能:

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

// 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>

1 个答案:

答案 0 :(得分:1)

我用字符串替换了ID,并做了一些小的更改以取消选中愿望清单中的项目,

$("#"+wish.items[currentIndex].id).parent().find($("label > input")).prop("checked", false);

并添加了一个函数,该函数不断显示wish变量中的项目。 检查以下代码:

    // 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]);
                            $("#"+wish.items[currentIndex].id).parent().find($("label > input")).prop("checked", false);
                            removeFromWish(wish.items[currentIndex].id);
                        }, 400);
                    });
                })();
            }
        };
        //Get Wish
        var getWish = function() {
            var myWish = wish;
            return myWish;
        };
    });

    setInterval(function() {
        if(wish.items.length > 0) {
            $("#wish_items").html(wish.items.map(function (elem) {
                return elem.id;
            }).join(", "));
        } else $("#wish_items").html('');
    },200);
    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='headphones' 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='backpack' 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>
    </div>
</div>

<div>Wish items: <span id="wish_items"></span></div>