【问题标题】:Using jQuery remove() to add items. When adding back same items, class changes are preserved使用 jQuery remove() 添加项目。重新添加相同的项目时,将保留类更改
【发布时间】:2013-01-08 12:10:33
【问题描述】:

我的 HTML 中有一些完全由 jQuery 生成的元素,然后在不再需要时将其删除。

类似的东西:

var div = $('<div/>').attr('id', 'addedItem');
$('body').append(div);

例如,当关闭时我们会这样做:

$('#addedItem').remove();

但是...在使用过程中,我们可能会更改addedItem 的类,因为它添加了另一个功能,例如,将tinyMCE 添加到textArea

$('#textAreaId').tinymce({ vars });

将富文本编辑器添加到文本区域(假设加载了所有正确的脚本),我在tinymce() 的末尾添加了一个新行:

$(applyTo).addClass('editorLoaded');

阻止代码尝试将编辑器添加到同一元素两次。

这一切都很好......但是......

如果我关闭此窗口并调用$('#addedItem').remove(); 行,然后稍后(不重新加载页面)我想重新添加到页面并再次显示,添加到元素的类仍然存在。

所以,简而言之。 jQuery 将 ID 为 addedItem 的元素添加到 body 中,对其进行处理并获得添加的类属性。使用 jQuery 完成后,将完全删除该元素。稍后,我们再次使用 jQuery 将 ID 为 addedItem 的新元素添加到 body,它是一个新元素,但它保留了在删除之前添加的类属性!

根据 jQuery DOCS remove() 的行为应该是:

除了元素本身,所有绑定的事件和jQuery 与元素关联的数据被删除。

我的意思是它应该删除使用 jQuery 以及数据等添加到元素中的任何类......也许我读错了,误解了,或者别的什么!

谁能帮我在浏览器内存/缓存/任何东西中删除这些元素和对它们的所有引用,以便我可以解决这个问题。

如果有帮助的话,jQuery 版本是 1.7.1

========== 编辑 > 更多代码添加 =================

上面概述了我的问题,然后是实际代码

// create a modal window with a top right X closer from any element
$.fn.makeModal = function (vars) {
    var theId = $(this).attr('id');
    var exists = false;
    try {
        if ($('#' + theId + '_wrap').length > 0) { // firstly check the element has already been "made modal"
            exists = true;
        };
    } catch (err) {
        exists = false;
    };

    if (!exists) { // if this is the first time
        var win = this;
        var h;
        var w;
        var persist;
        var alert;
        if (vars) {
            h = vars.height;
            w = vars.width;
            persist = vars.persist;
            alert = vars.alert;
        };
        if (typeof h == "string") {
            h = (h.replace('px', '') * 1); // clean out px if dimensions posted in px
        };
        if (typeof w == "string") {
            w = (w.replace('px', '') * 1); // clean out px if dimensions posted in px
        };
        var hRatio = 0.70;
        var wRatio = 0.5;
        var minW = 480;
        if (!h) { h = $(window).height() * hRatio }; // default case if no height passed
        if (!w) {
            w = $(window).width() * wRatio;
            minW = 480;
            if (w < minW) { w = minW };
        }; // default case if no width passed

// **** END BASIC VARIABLES

        var wrapper = $('<div/>').attr('id', theId + '_wrap').addClass('modalContainer').css({ 'top': ($(window).height() - h) / 2, 'left': ($(window).width() - w) / 2, 'width': w, 'height': h }); // create a wrapper for the main content
        var close = $('<span/>').addClass('closeModal').html('X').css({ 'z-index': getMaxZIndex() + 5 });

// creat  close button
        if (alert) {
            $(close).addClass('alert');
            $(wrapper).addClass('alert');
        } else {
            $(close).addClass('cross');
        };
        if (persist) {
            $(wrapper).addClass('persist');
        }; // persist variable allows you to determine whether to delete or simply hide element on close
        $(win).addClass('modalContent').css({ 'display': 'block', 'width': w - 20, 'height': h - 20 }).appendTo(wrapper);

        $('body').append(wrapper).opaqueBg();

        $(wrapper).prepend(close).fadeIn('fast').css({ 'z-index': getMaxZIndex() + 3 });
        $(close).modalCloser();

        $(document).on('keyup', function (e) {
            if (e.keyCode == 27) {
                closeModal(wrapper);
                $(document).unbind('keyup');
            };
        });
    } else {
        $('body').opaqueBg();
        $('#' + theId + '_wrap').fadeIn('fast') // .children().css({ 'display': 'block' });
    };
    // END OF MODAL WINDOWS
};

上面的 jQuery 函数使用任何动态创建的元素或其他方式创建一个模态窗口。

关闭等相关函数:

//  top right X closer actions
$.fn.modalCloser = function (callBack) {
    $(this).bind('click', function () {
        $(this).closest('div.modalContainer').fadeOut(function () {
            closeModal(this, callBack);
        });
    });
};
// close modal element by item
function closeModal(ele, callBack) {
    if (!ele) {
        ele = '.modalContainer'
    };
    if ($(ele).hasClass('noClose')) {
        alert("Please wait... we're working on something.");
    } else {
    $(ele).fadeOut(function () {
        var nextZ = getMaxZIndex('.modalContainer');
        if (nextZ > 0) {
            $('#screenBlank').css({ 'z-index': nextZ });
        } else {
            $('#screenBlank').fadeOut(function () { $(this).remove(); });
        };
        if (!$(this).hasClass('persist')) {
            $(this).remove();
        };
        if (callBack) {
            callBack();
        };
    });
    };
};
// end modal window controls

// **************************************************************************************************************************************************************** 

// create opaque background for modal window to sit on
$.fn.opaqueBg = function () {
    $('#screenBlank').remove();
    var z = getMaxZIndex() + 2;
    var sb = $('<div/>').attr('id', 'screenBlank').addClass('noPrint centreLoader').css({ 'display': 'none', 'position': 'absolute', 'text-align': 'center', 'z-index': z, 'background-color': 'rgba(10, 0, 0, 0.7)', 'width': '100%', 'height': $(document).height(), 'top': '0px', 'left': '0px' });
    $('body').prepend(sb);
    $(sb).fadeIn().bind('click', function () {
        closeModal('.modalContainer');
    });
};

// find the maximum z-Index of elements on the page, used to ensure tooltips are always shown above anything else
// note, this will only work if major containing elements have explicitly set z-index
function getMaxZIndex(ele) {
    if (!ele) {
        ele = "div";
    };
    var zIndexMax = 0;
    $(ele).each(function () {
        if ($(this).css('display') != "none") {
            var z = parseInt($(this).css('z-index'));
            if (z > zIndexMax) { zIndexMax = z };
        };
    });
    return zIndexMax;
};
// end finding maximum z-index 

因此,以上所有内容都是我项目中用于各种目的的通用函数集。

发布这篇文章的特定目的是在应用了tinymce 的模式窗口中创建一个文本区域,其工作原理如下:

    $('#notePad .plus').on('click', function () {
        var h = $('<h2/>').html('Add Note');
        var txt = $('<textarea/>').attr('id', 'noteEditorContent').attr('name', 'newNote').css({ 'width': '100%', 'height': '400px' });
        var wrpper = $('<div/>').css({ 'width': '750', 'height': '380', 'margin': 'auto' }).append(txt);
        var button = $('<span/>').addClass('greenButton').html('Save').css({ 'float': 'right', 'margin': '40px 20px 0px 20px', 'width': '80px' }).bind('click', function () {
            saveStaffNote($('#noteEditorContent').val(), true);
        });
        var div = $('<div>').attr('id', 'notePadEditor').append(h).append(wrpper).append(button);
        $(txt).richEditor('simple', function () {
            $(div).makeModal({ 'width': '800', 'height': '530', 'persist': true });
            // CALLING THE makeModal() function above
        });
    });

最后,tinymce 的应用就是这个函数:

// === loading Rich Text Editors //
$.fn.richEditor = function (theTheme, callBack) {
    var applyTo = this;
    var tinyMceVars = {
        // Location of TinyMCE script
        script_url: '/Admin/Plugins/richEditor/tiny_mce.js',
        // General options
        theme: theTheme,
        plugins: "autolink,lists,pagebreak,style,layer,table,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,searchreplace,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,advlist",
        // Theme options
        theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,formatselect,fontselect,fontsizeselect,|,bullist,numlist,|,undo,redo,|,code,preview,fullscreen,|,cleanup,help",
        theme_advanced_buttons2: "cut,copy,paste,pastetext,|,insertdate,inserttime,|,link,unlink,anchor,image,|,forecolor,backcolor,|,search,replace",
        theme_advanced_buttons3: "tablecontrols,|,hr,removeformat,visualaid,|,charmap,emotions,iespell",
        theme_advanced_toolbar_location: "top",
        theme_advanced_toolbar_align: "left",
        theme_advanced_statusbar_location: "bottom",
        theme_advanced_resizing: true,
        relative_urls: false,
        remove_script_host: false,
        document_base_url: window.location.protocol + "//" + window.location.hostname,
        external_link_list_url: window.location.protocol + "//" + window.location.hostname + "/Admin/Scripts/Lists/link_list.js",
        external_image_list_url: window.location.protocol + "//" + window.location.hostname + "/Admin/Scripts/Lists/image_list.js"
    };

    if ($(applyTo).hasClass('editorLoaded') == false) {
        try { // try to apply the editor, if fails it's because the scripts are not loaded, so load them!
            $(applyTo).tinymce(tinyMceVars);
        } catch (err) {
            $.getScript("/Admin/Plugins/richEditor/jquery.tinymce.js", function () {
                $(applyTo).tinymce(tinyMceVars);
            });
        } finally { // finally apply richEdit class to avoid re-writing and perform a callback if required
            $(applyTo).removeClass('richEdit').addClass('editorLoaded');
            if (callBack) {
                callBack();
            };
        };
    };
};

【问题讨论】:

  • 有趣的问题。如果省略tinymce,它是否还记得课程?
  • 我很难相信你对正在发生的事情的分析是正确的。你能通过一个简单的测试来复制这种行为吗?
  • “我的意思是它应该删除添加到元素中的所有类...” 不,它会删除存储在jQuery.cache 中的数据。它不涉及元素上的任何属性,除了拥有jQuery.cache 索引的属性。您需要手动删除类。
  • ...如果问题是您需要在将插件重新插入页面后重新应用插件,然后尝试使用.detach() 而不是.remove(),这样会保留所有数据删除它,所以如果你再次插入它,它仍然会有它原来的行为。
  • Here is a jsbin 证明当一个元素被移除时,随后添加具有相同“id”值的元素不会导致先前添加的类被恢复。您确定您没有添加具有 same “id”值的 multiple 元素吗?

标签: javascript jquery dom removeclass removeall


【解决方案1】:

我相信您的问题是您正在将类添加到一个 jQuery 对象,该对象也被名为 div 的变量引用。尝试将该变量隐藏在函数中(javascript 具有函数范围)。

试试这个:

var addItem = function(){
    var div = $('<div/>').attr('id', 'addedItem');
    $('body').append(div);
};

addItem();
$('#addedItem').addClass('weeeeeee');
$('#addedItem').remove();
addItem();

【讨论】:

  • 啊……这里可能会有所作为。我的完整代码比我发布的(自然)更复杂,但这可能是原因,我将进一步深入研究! :-)
  • 我认为这是正确的答案......但我无法实现它。我正在尝试创建通用函数来显示和隐藏动态添加的元素。我现在已经重新设计了一些东西,所以它只是隐藏并且根本不 remove() 元素。
  • @JamieHartnoll 你能发布更多代码吗?也许有一种方法可以实现这样的东西。
  • 好的,我已经发布了我的完整代码。创建我正在处理的整个应用程序涉及到几个函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-28
  • 2018-10-16
相关资源
最近更新 更多