简体   繁体   English

jQuery追加后删除元素

[英]Jquery remove element after append

So i was just wondering. 所以我只是想知道。 Why does this work: 为什么这样做:

$("input[name='edit-meta']").keyup(function(e){
    if(e.keyCode=='32'||e.keyCode=='13'){
        var clicked=$(this);
        var tag=$(this).val();
        clicked.siblings("#edit-meta").append('<span style="background:<?php echo $ad_details_arr[9]?>;color:<?php echo $ad_details_arr[8]?>" class="tag">'+tag.slice(0,-1)+'<a href="#" class="remove" style="background:<?php echo $ad_details_arr[10]?>;color:<?php echo $ad_details_arr[8]?>;margin:5px">x</a></span>');
        clicked.val("");
    }
    $("a.remove").on("click",function(e){
        e.preventDefault();
        var clicked=$(this);
        clicked.closest("span.tag").fadeOut(function(){
            $(this).remove();
        });
    });
});

And not this: 而不是这样:

$("input[name='edit-meta']").keyup(function(e){
    if(e.keyCode=='32'||e.keyCode=='13'){
        var clicked=$(this);
        var tag=$(this).val();
        clicked.siblings("#edit-meta").append('<span style="background:<?php echo $ad_details_arr[9]?>;color:<?php echo $ad_details_arr[8]?>" class="tag">'+tag.slice(0,-1)+'<a href="#" class="remove" style="background:<?php echo $ad_details_arr[10]?>;color:<?php echo $ad_details_arr[8]?>;margin:5px">x</a></span>');
        clicked.val("");
    }
});
$("a.remove").on("click",function(e){
    e.preventDefault();
    var clicked=$(this);
    clicked.closest("span.tag").fadeOut(function(){
        $(this).remove();
    });
});

I thought the .on would be sufficient to allow me to perform handlers yet created just like .live does. 我认为.on足以让我执行像.live这样创建的处理程序。

Also stated in the jquery .on page. 还在jquery .on页面中说明。

" ... ability to handle events on descendant elements not yet created " “ ...处理尚未创建的后代元素上的事件的能力”

You can use this:- 您可以使用以下方法:

$(document).on("click" , "a.remove" ,function(e){
    e.preventDefault();
    var clicked=$(this);
    clicked.closest("span.tag").fadeOut(function(){
        $(this).remove();
    });
});

The above thing will not work because a.remove is not available in the DOM. 由于a.remove在DOM中不可用,因此上述操作将无效。

The first example work because you are attaching event to a.remove after it is added to the DOM. 第一个示例工作是因为将事件添加到DOM之后将事件附加到a.remove。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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