简体   繁体   English

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

[英]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时,它不起作用:

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 : 现在,请注意,可能有一个比迭代所有filesId绑定功能简单得多的解决方案,您可以直接在所有匹配的元素上进行绑定并从clicked元素id推导出filesId

$("[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 您正在调用该函数,是将其返回的值(在本例中为undefined)作为事件处理函数传递,而不是将其作为事件处理函数传递

$("#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 同样,参数filesId看起来像一个封闭变量,如果您可以共享更多有关该问题的上下文,我们可以使外观更好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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