jQuery-加载时运行更改功能

时间:2019-04-03 21:44:38

标签: javascript jquery

在愿望清单ui函数中,我append checking .wish-btn到愿望清单。我想模拟已经添加到列表中的项目,因此我需要在加载时运行该函数,以便所有项目都为checked

如何在load上运行该函数,以便所有项目均为:

  1. 已检查
  2. 附加到列表

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(".product");
      $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(".product");
    $parent
      .find(".wish-icon")
      .first()
      .removeClass("active")
      .attr("data-prefix", "far");
    //Update popup wish
    updateWish(wish);
  };

  var getProductValues = function(element) {
    var productId = $(element)
      .closest(".product")
      .find(".item__title")
      .attr("id");
    var productImg = $(element)
      .closest(".product")
      .find(".item__img")
      .attr("src");
    var productName = $(element)
      .closest(".product")
      .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 class='wish__item'>" +
        '<div class="wish__thumb">' +
        "<img src='" +
        wish.items[i].img +
        "' />" +
        "</div>" +
        '<div class="wish__info">' +
        '<div class="wish-name">' +
        wish.items[i].name +
        "</div>" +
        "</div>" +
        '<div class="wish__remove">' +
        '<label class="wish__label">' +
        '<input type="checkbox" id="my-wish-remove' +
        i +
        '" class="my-wish-remove" aria-hidden="true">' +
        "<i class='fas fa-heart'></i>" +
        "</div>" +
        "</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).parents().find($(".wish-btn > input")).prop("checked", false);
            removeFromWish(wish.items[currentIndex].id);
          }, 400);
        });
      })();
    }
  };


  //Get Wish
  var getWish = function() {
    var myWish = wish;
    return myWish;
  };
});
img {
  width: 50px;
}

.my-wish-add {
  font-family: "Font Awesome\ 5 Pro";
  font-weight: 900;
}

.wish-btn {
  position: relative;
}

.wish-btn input {
  position: absolute;
  opacity: 0;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  cursor: pointer;
}

.wishlist__list {
  right: 0;
  width: 320px;
  position: absolute;
  padding: 20px;
}
<script src="https://pro.fontawesome.com/releases/v5.3.1/js/all.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.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="product">
    <div id='headphones' class='item__title'>Item 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="product">
    <div class="items__cart">
      <div id='backpack' class='item__title'>Item 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 class="product">
    <div class="items__cart">
      <div id='handbag' class='item__title'>Item 3</div>
      <img class="item__img" src="https://qph.fs.quoracdn.net/main-qimg-de7d9680c4460296e461af9720a77d64">
      <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>

`

2 个答案:

答案 0 :(得分:1)

创建变更事件监听器后,可以通过链接change()(不带参数)来立即触发变更。

使用prop('checked', true)将对其进行检查,您也可以对其进行链接

$(selector).on('change', function(evt){
   // do stuff when change occurs

  // now check it and trigger change
}).prop('checked', true).change()

答案 1 :(得分:1)

按照charlietfl的回答,那么您会得到一个错误:

  

TypeError:getWish不是函数

然后,您必须将library(gridExtra) library(dplyr) # just for pipes plotlist(mtcars, hp, c("mpg","cyl","disp")) %>% grid.arrange(grobs = ., left = "HP") 事件处理程序移至changegetWish函数下方的底部,因为需要先声明它们以供事件处理程序使用。

updateWish
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(".product");
      $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(".product");
    $parent
      .find(".wish-icon")
      .first()
      .removeClass("active")
      .attr("data-prefix", "far");
    //Update popup wish
    updateWish(wish);
  };

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

  //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 class='wish__item'>" +
        '<div class="wish__thumb">' +
        "<img src='" +
        wish.items[i].img +
        "' />" +
        "</div>" +
        '<div class="wish__info">' +
        '<div class="wish-name">' +
        wish.items[i].name +
        "</div>" +
        "</div>" +
        '<div class="wish__remove">' +
        '<label class="wish__label">' +
        '<input type="checkbox" id="my-wish-remove' +
        i +
        '" class="my-wish-remove" aria-hidden="true">' +
        "<i class='fas fa-heart'></i>" +
        "</div>" +
        "</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).parents().find($(".wish-btn > input")).prop("checked", false);
            removeFromWish(wish.items[currentIndex].id);
          }, 400);
        });
      })();
    }
  };

  //Get Wish
  var getWish = function() {
    var myWish = wish;
    return myWish;
  };

  // Move this block to the bottom after you have defined all functions
  $(".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);
    }
  }).prop('checked', true).change();
});
img {
  width: 50px;
}

.my-wish-add {
  font-family: "Font Awesome\ 5 Pro";
  font-weight: 900;
}

.wish-btn {
  position: relative;
}

.wish-btn input {
  position: absolute;
  opacity: 0;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  cursor: pointer;
}

.wishlist__list {
  right: 0;
  width: 320px;
  position: absolute;
  padding: 20px;
}