我有这个加载内容的脚本,然后应该绑定删除链接以删除内容。
然而,我发现它没有与删除链接绑定,即使那时我把代码放在一个应该重新绑定的函数中。
$(document).ready(function() {
function loadImages() {
$.get('/management/image/get/site_id/1/area/News', function(data) {
$("#existing-images").html(data);
});
$(".deleteImage").click(function() {
id = $(this).attr('id'); id = id.split('_');
alert(id);
/*$.post(second_url+'id/'+id, '', function(theResponse) {
$("#image_"+id+"").remove();
});*/
});
}
$("#fileInput").uploadify({
'uploader' : '/library/jquery/uploadify/uploadify.swf',
'script' : '/gallery/image/area/site_id/<?php echo $site->id; ?>/area/<?php echo $this->area; ?>',
'cancelImg' : '/library/jquery/uploadify/cancel.png',
'folder' : '/images/Image/',
'multi' : true,
'onAllComplete' : function(e, queueId, file, response, data) {
$('#fileInput').uploadifyClearQueue();
loadImages();
},
});
loadImages();
});
答案 0 :(得分:1)
您在ajax请求完成之前绑定了删除链接。
答案 1 :(得分:1)
您可以使用$.live函数动态绑定删除链接,而不是每次发出请求时都这样做。
尝试类似:
//..init code
$(".deleteImage").live('click',function() {
id = $(this).attr('id'); id = id.split('_');
alert(id);
});
function loadImages() {
$.get('/management/image/get/site_id/1/area/News', function(data) {
$("#existing-images").html(data);
});
}
//more code here...
答案 2 :(得分:0)
这是因为ajax调用的异步性质。
您编写的代码尝试将click事件绑定到尚未注入DOM的按钮
尝试将代码更改为:
$(document).ready(function() {
function loadImages() {
$.get('/management/image/get/site_id/1/area/News', function(data) {
$("#existing-images").html(data);
$(".deleteImage").click(function() {
id = $(this).attr('id'); id = id.split('_');
alert(id);
/*$.post(second_url+'id/'+id, '', function(theResponse) {
$("#image_"+id+"").remove();
});*/
});
});
}
$("#fileInput").uploadify({
'uploader' : '/library/jquery/uploadify/uploadify.swf',
'script' : '/gallery/image/area/site_id/<?php echo $site->id; ?>/area/<?php echo $this->area; ?>',
'cancelImg' : '/library/jquery/uploadify/cancel.png',
'folder' : '/images/Image/',
'multi' : true,
'onAllComplete' : function(e, queueId, file, response, data) {
$('#fileInput').uploadifyClearQueue();
loadImages();
},
});
loadImages();
});
将绑定移动到$.get
调用的成功回调中,确保在绑定发生之前注入了新的html。
另外尝试使用delegate而不是绑定到元素,这样您就不需要一直重新绑定