在jQuery中重新删除已删除的项目

时间:2014-10-15 18:26:03

标签: jquery

我使用jQuery填充了一系列复选框中的项目。

如果有支票或取消选中,我可以追加并删除列表项。 我遇到的问题是当我使用.remove()时,如果我尝试去重新追加列表项,则没有动作。列表项不会重新附加。

下面是我正在使用的jQuery,但是在删除列表项后重新追加它的逻辑是什么。

   $('#attendeePicker .zInput.zCheckbox ,#attendeePicker2 .zInput.zCheckbox').on("click", function(e) {
            var parentSection = $(this).parents("section").attr("id");


            var attendeename = $(this).find('input').data("attendeename"),
                productname = $(this).find('input').data("productname"),
             optionprice = $(this).find('input').data("optionprice"),
                /* get jQuery selector for list from data */
                //jQId = "#" + data.,
                $list = $(".CartList li." + attendeename).find('.itemList');
            //alert($list)


            if ($(this).hasClass("zSelected")) {
                /* add element to list if selelected*/

                var li = '<li class="animated bounceIn"><span class="itemTime">' + $("#" + parentSection + " .timelist .zInput.zSelected input").val() + ' - ' + '</span><span class="itemName">' + productname + '</span><span class="itemPrice">' + optionprice + '</span></li>';
                //  var li = '<li class="animated bounceIn"><span class="itemTime">' + $(".timelist .zInput.zSelected input").val() + ' - ' + '</span><span class="itemName">' + productname + '</span><span class="itemPrice">' + optionprice + '</span></li>';

                $list.append(li);

            } else {
                /* empty list if unchecked*/

                //Empties the ilist BUT we don't want that.
                // $list.empty(); // completely empties the list
                $list.remove(li);  //only removes the single item. I want this.

            }

        });  

2 个答案:

答案 0 :(得分:1)

当你删除一个元素时,它会从DOM中删除,因此你无法重新附加它。

您可以通过以下方式实现:

方法1

首先克隆元素(.clone())然后将其删除。使用克隆的对象重新附加。

工作样本:http://jsfiddle.net/pvod0gam/1/

var $elem;
$("#check").click(function(){
    if($(this).prop("checked")){
        $elem = $("#elem").clone();
        $("#elem").remove();
    }else{
        $("body").append($elem);
    }
});

方法2

切换元素的显示(.toggle())。基本上显示/隐藏复选框状态。

工作样本:http://jsfiddle.net/9mfv67gq/

$("#check").click(function(){
    $("#elem").toggle();
});

答案 1 :(得分:0)

只是.hide()和.show()子列表基于您正在检查/取消选中的复选框。