简体   繁体   中英

Remove DOM element with JQuery after it has been Appended

I have tried numerous methods, but I am not able to remove the chat_box after I click away from it..

$(".attribute").click(function(){
                var chatVal = "edit " + $(this).data("attr") + " then press enter",     
                chatDiv = "<input type='text' name='chat_box' value='' id='chat_box' placeholder='" + chatVal + "'></input>";

                $(this).append(chatDiv);
            });

$(document).click(function(){

                //how to remove??

            });

What is $(".attribute") ? If its a form element, you can listen for the blur event.

$(".attribute").on('blur',function() { $("#chatbox").remove(); });

After you append an item to the DOM, you cannot immediately remote it as it needs time to update. Try wrapping your remove code in a setTimeout.

$(document).click(function(){
   setTimeout(function () { $('#chat_box').remove(); }, 10);
});

Besides that, everything looks fine. If this doesn't work, setup a jsfiddle to demonstrating the issue further.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM