在我的情况下,on()在绑定函数中不起作用

use*_*088 1 javascript jquery

这很有效

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

但是当我试图将它分开并使用函数时它不起作用:

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

$("#closePreviewPhoto" + filesId).on('click', removePhoto(filesId));
Run Code Online (Sandbox Code Playgroud)

我的错在哪里?

Den*_*ret 5

您传递函数调用的结果而不是函数.

更改

$("#closePreviewPhoto" + filesId).on('click', removePhoto(filesId));
Run Code Online (Sandbox Code Playgroud)

$("#closePreviewPhoto" + filesId).on('click', function(){
    removePhoto(filesId)
});
Run Code Online (Sandbox Code Playgroud)

现在,请注意,可能有一个比迭代所有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');
});
Run Code Online (Sandbox Code Playgroud)