简体   繁体   中英

.remove(); jquery appended div

http://jsfiddle.net/VTD9P/2/

$("button").click(function(){
    $("body").append('<div  class="vidminclose">X</div>');
});
$(".vidminclose").click(function(){
    $(this).remove();
});

​ ​why is it when i click the div.miniclose it is that it wont remove... and what is a way of getting around it. and i have looked at similar questions but i can't seem to fit their solutions to fix my problem.

.vidmeclose does not exist to have the click event bound to it when .click is fired since it is appended to the DOM later. You need to do one of two things (and this also depends on your jQuery version).

Solution #1

$("#button").click(...
    $("body").append(...
    $(".vidmeclose").click(...

http://jsfiddle.net/VTD9P/4/

Solution #2

$("button").click(...

$("body").on('click', '.vidmeclose', function () ...

Note that it could be useful to use a more specific selector in the second example, if it's available.

http://jsfiddle.net/VTD9P/5/

it's because vidminclose does not exist yet. need to use live (older jquery) or on (newer jquery).

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