2014-03-13 39 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'元素它自己的獨特類 - 以減少選擇器語法。 –

相關問題