2014-03-13 37 views
0
$(".spanCont:first .collection_shop").on("click",function(){ 
      var current_item = $(this); 
      $.ajax({ 
       url: "ajax/abc.php", 
       type: "POST", 
       dataType: 'html', 
       data: {collection_id: current_item.attr("value")}, 
       beforeSend: function(xhr) { 
        current_item.replaceWith("<div id='temp_div'></div>"); 
       } 
      }).done(function(data){ 
       $(".spanCont:first .span-2, .spanCont:first input").remove(); 
       $("#temp_div").replaceWith(data); 
      }); 
     }); 

此代码应该适用于类.collection_shop的所有静态和动态点击元素,但它只适用于静态元素。jquery事件不适用于动态元素

回答

1

你应该使用event delegation

$(document).on("click",".spanCont:first .collection_shop",function(){ 
    //some operation 
}); 

它有助于ÿ OU附加处理程序动态元素

2

您需要动态元素的on()的其他(delgation)版本。委派事件动态元素的静态父母或你可以使用文档/体等

$(document).on("click", ".spanCont:first .collection_shop", function(){ 
    var current_item = $(this); 
    $.ajax({ 
     url: "ajax/abc.php", 
     type: "POST", 
     dataType: 'html', 
     data: {collection_id: current_item.attr("value")}, 
     beforeSend: function(xhr) { 
      current_item.replaceWith("<div id='temp_div'></div>"); 
     } 
    }).done(function(data){ 
     $(".spanCont:first .span-2, .spanCont:first input").remove(); 
     $("#temp_div").replaceWith(data); 
    }); 
}); 

你有

$(".spanCont:first .collection_shop").on("click",function(){ 

你需要,事件代表团

$("static-parent-selector").on("click", .spanCont:first .collection_shop, function(){ 

委托事件具有的优点是,他们可以处理来自 后代元素的事件,这些事件元素在稍后的时间点添加到文档中我。通过 采摘这是保证出席 委派的事件处理程序连接时的元素,你可以使用委派事件 避免需要经常重视和移除事件处理程序,jQuery Docs

2

使用event delegation

$(document).on("click",".spanCont:first .collection_shop",function(){ 
//code 
}); 
2

使用.on()

使用Event Delegation

语法

$(elements).on(events, selector, data, handler); 

这样

$(document).on("click",".spanCont:first .collection_shop",function(){ 
    // code here 
}); 

$('parentElementPresesntAtDOMready').on('click','.spanCont:first .collection_shop',function(){ 
    // code here 
}); 
1

另一种方法,一点仁慈你的用户界面比从根“文件”设置事件代表团

斯普利特AJAX从监听到它自己的功能,并创建一个监听器函数在DOM被ajax调用中的代码更新后'侦听'。

这是很好的反正分离(比如在要触发从别的Ajax请求的未来)

function ajaxCall() { 

    /* ... do the ajax call and return data */ 
.....done(function() { 

    /* update the DOM et al */ 

    /* reset the listener */ 
    listen(); 

}); 
} 

function listen() { 
$(".spanCont:first .collection_shop").off("click").on("click",function(){ 
    ajaxCall(); 
}); 
} 
/* start */ 
listen(); 

像 - http://jsbin.com/foruyapi/1/edit

+0

*如果这些'.collection_shop'添加元素动态 - 值得给予':first'元素它自己的独特类 - 以减少选择器语法。 –

相关问题