2014-02-27 79 views
1

这是工作上()不绑定功能在我的情况下工作

$("#closePreviewPhoto" + filesId).on('click',function(){ 
     $('#list' + filesId).html(""); 
     $('#files' + filesId).val(""); 
     $('.thumb-canvas' + filesId).css('display','none'); 
     }); 

,但它不工作时,我试图分开它,并使用功能:

function removePhoto(filesId){ 
    $('#list' + filesId).html(""); 
    $('#files' + filesId).val(""); 
    $('.thumb-canvas' + filesId).css('display','none'); 
} 

$("#closePreviewPhoto" + filesId).on('click', removePhoto(filesId)); 

哪里是我的错误?

回答

2

您呼叫的功能通过由它返回的值(在这种情况下未定义)作为事件处理程序,而不是把它当作一个事件处理程序

$("#closePreviewPhoto" + filesId).on('click', function(){ 
    removePhoto(filesId) 
}); 

而且参数filesId看起来像一个封闭变量,如果你可以分享更多的上下文来解决问题,我们可以有更好的看看

5

你正在传递函数调用的结果而不是函数。

变化

$("#closePreviewPhoto" + filesId).on('click', removePhoto(filesId)); 

$("#closePreviewPhoto" + filesId).on('click', function(){ 
    removePhoto(filesId) 
}); 

现在,请注意,可能有一个更简单的解决方案,而不是遍历所有的filesId绑定的功能,你可以做直接对所有的绑定匹配元素并从点击元素中推导出filesId id:

$("[id^=closePreviewPhoto]").on('click', function(){ 
    var filesId = this.id.slice("closePreviewPhoto".length); 
    $('#list' + filesId).html(""); 
    $('#files' + filesId).val(""); 
    $('.thumb-canvas' + filesId).css('display','none'); 
}); 
相关问题