【问题标题】:trying to remove and store and object with detach()尝试使用 detach() 删除和存储对象
【发布时间】:2012-02-06 21:11:12
【问题描述】:

我正在尝试删除一个对象并将其存储(以防用户稍后想要检索它)。我已经尝试将对象存储在一个变量中,就像它在下面的线程中所说的那样:

How to I undo .detach()?

但是detach() 不会从 DOM 中删除元素或存储它。我也没有收到任何错误消息。这是我用来分离元素的代码:

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

问题的关键就在这里:http://jsfiddle.net/pScJc/

(分离的按钮是右边的“+”按钮,应该是添加一个div,再次点击时分离。)

【问题讨论】:

    标签: javascript jquery detach


    【解决方案1】:

    查看您的代码,我认为您不需要 detach 来实现您想要实现的目标。

    试试这个代码。

        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

    【讨论】:

    • @ShankarSangoli--有趣...但出于好奇,我是不是用错了detach()
    • 您的 detach 代码没有被执行,因为您正在取消绑定 click 处理程序。
    猜你喜欢
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 2014-04-06
    • 1970-01-01
    • 1970-01-01
    • 2012-12-02
    相关资源
    最近更新 更多