简体   繁体   中英

on() doesn't work in binding function in my case

This is working

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

but it doesn't work when I tried to separate it and use function :

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

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

where is my mistake?

You're passing the result of the function call instead of the function.

Change

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

to

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

Now, note that there's probably a much simpler solution than to iterate over all your filesId to bind a function, you can do the binding directly on all matching elements and deduce filesId from the clicked element 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');
});

You are calling the function as passing the value returned by it(in this case undefined) as the event handler, instead of passing it as a event handler

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

Also the parameter filesId looks like a closure variable, if you can share more context to the problem we can have a better look

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM