trying to remove and store and object with detach()

只愿长相守 提交于 2019-12-25 01:28:48

问题


I am trying to remove an object and store it (in case a user wants to retrieve it later). I have tried storing the object in a variable like it says in the thread below:

How to I undo .detach()?

But the detach() does not remove the element from the DOM or store it. I am also not getting any error messages. Here is the code I am using to detach the element:

function MMtoggle(IDnum) {
        var rowID = "row" + IDnum;
        var jRow = '#' + rowID;
        thisMMbtn = $(jRow).find(".addMMbtn");
        var light = false;
        var that = this;
        if (light == false) {
            thisMMbtn.bind("click",
                function() {
                    var thisRow = $(this).closest(".txtContentRow");
                    var thisTxt = thisRow.find(".txtContent");
                    var cellStr = '<div class = "mmCell prep"></div>';
                    $(cellStr).appendTo(thisTxt);
                    $(this).unbind("click");
                    light = true;
                }
            );
        }
        else {
            thisMMbtn.bind("click",
                function() {
                    var thisRow = $(this).closest(".txtContentRow");
                    thisMM = thisRow.find(".mmCell");
                    SC[rowID].rcbin = thisMM.detach(); //here is where I detach the div and store it in an object
                    $(this).unbind("click");
                    light = false;
                }
            );
        }
    }

    MMtoggle(g.num);

A fiddle of the problem is here: http://jsfiddle.net/pScJc/

(the button that detaches is the '+' button on the right. It is supposed to add a div and then detach it when clicked again.)


回答1:


Looking at your code I don't think so you need detach for what you are trying to achieve.

Instead try this code.

    thisMMbtn.bind("click",
        function() {
            var thisRow = $(this).closest(".txtContentRow");
            var thisTxt = thisRow.find(".txtContent");
            var $mmCell = thisTxt.find('.mmCell');
            if($mmCell.length == 0){
                $mmCell = $('<div class = "mmCell prep"></div>')
                          .appendTo(thisTxt).hide();
            }
            $mmCell.toggle();
            //$(this).unbind("click");
        }
    );

Demo



来源:https://stackoverflow.com/questions/9167318/trying-to-remove-and-store-and-object-with-detach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!