如何使用jQuery()删除元素

时间:2017-06-29 04:51:41

标签: javascript jquery

我正在尝试在选中复选框时添加元素,并在用户取消选中该框时删除该元素。

这是我的代码:

$(document).ready(function() {

      var increment = 0;
      var artist_to_compare = new Set();

      $(document).on("change", ".checkbox", function() {
          increment += this.checked ? 1 : -1;

          if (!this.checked) {

              // // delete the artist from the list of comparison
              $(element_to_delete).remove();
              artist_to_compare.delete(this.name);
              var element_to_delete = "." + this.name;
              console.log(element_to_delete);

          } else {

              // Add the artist to the list of comparison
              artist_to_compare.add(this.name);
              var element_to_add = '<p class="' + this.name + '">' + this.name + '</p>';
              console.log(element_to_add);
              $(".artistToCompare").after(element_to_add);

          }

          if (increment >= 2) {
              console.log(artist_to_compare);
              // enable the compare button

          }
      });
  });

我能够正确添加元素,但我无法将其删除。请帮忙!

2 个答案:

答案 0 :(得分:2)

在定义$(element_to_delete).remove();

之前,您已撰写element_to_delete
artist_to_compare.delete(this.name);
  var element_to_delete = "." + this.name;
  console.log(element_to_delete);
$(element_to_delete).remove();

答案 1 :(得分:0)

是的,拉胡尔是对的。您在定义之前使用remove()函数删除element_to_delete。结帐以下代码。

$(document).ready(function() {

    var increment = 0;
    var artist_to_compare = new Set();

    $(document).on("change", ".checkbox", function() {
        increment += this.checked ? 1 : -1;

        if (!this.checked) {

            // delete the artist from the list of comparison
            var element_to_delete = "." + this.name;
            console.log(element_to_delete);
            $(element_to_delete).remove();
            artist_to_compare.delete(this.name);

         } else {

            // Add the artist to the list of comparison
            artist_to_compare.add(this.name);
            var element_to_add = '<p class="' + this.name + '">' + this.name + '</p>';
            console.log(element_to_add);
            $(".artistToCompare").after(element_to_add);

        }

        if (increment >= 2) {
            console.log(artist_to_compare);
            // enable the compare button

        }
    });
});