簡體   English   中英

使用jQuery remove()添加項目。 重新添加相同項目時,將保留類別更改

[英]Using jQuery remove() to add items. When adding back same items, class changes are preserved

我的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 ,對其進行了處理,並為其添加了class屬性。 jQuery完成后,將其完全刪除。 稍后,我們再次使用jQuery向body添加ID為addedItem的新元素,這是一個新鮮元素,但它保留了刪除前添加的class屬性!

根據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();
            };
        };
    };
};

我相信您的問題是,您正在將該類添加到jQuery對象,該對象也被稱為div的變量引用。 嘗試將變量分散在函數內部(javascript具有函數作用域)。

試試這個代替:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM