开发者

After append() how to bind a click event to just added element

开发者 https://www.devze.com 2022-12-23 17:08 出处:网络
I have this code $(\".delete2\").click(function() { $(\'#load2\').fadeIn(); } I have dynamically added item via this return

I have this code

$(".delete2").click(function() {
  $('#load2').fadeIn();
}

I have dynamically added item via this return

addSubcategory = function(){
        sucategorynameval = $("#sucategoryname").val(); 
        categoryId        = $("#addcategoryid").val(); 
        $.get("process-add-subcat.php", { "a开发者_运维问答ction": "add_subcategory", "sucategoryname": sucategorynameval, "categoryId":categoryId },
               function(data){
                 //$("#main-cat-"+categoryId).load(location.href+"&pageExclusive=1 #main-cat-"+categoryId+">*","");
                 $("#main-cat-"+categoryId).append(data);
                 $("#addcategoryid").val(''); 
                 $("#sucategoryname").val(''); 
               }); 

The returned data contains delete2 classed item.

How do I apply the click event to the newly added item?


well you can just rebind it with the same click function you have used before or you use .live() http://api.jquery.com/live/


Replace

$(".delete2").click(function() {
    $('#load2').fadeIn();
}

with

$(".delete2").live('click', function() {
    $('#load2').fadeIn();
});

This way the click event is bound to all existing an in the future created elements with class .delete2


$(<parent selector>).on('click', '.delete2', function() { alert('test'); });

Change the parent selector to the id or class of the parent element

0

精彩评论

暂无评论...
验证码 换一张
取 消