繁体   English   中英

jQuery在另一个事件处理程序中设置事件处理程序

[英]jquery set event handler in another event handler

我有一个包含很多图像和一个js图像编辑器的网站。 我要做的只是在图像上双击以在编辑器中将其打开,然后按保存(我的编辑器下面的按钮会生成图像数据URL)以根据编辑器对其进行更新。 现在编码。

$("body").delegate("img",'dblclick', function(){
        var parent = $(this).parent()
        var input = parent.find("input[name$='-source']").first();
        var source = input.val();
        var self = $(this);

        $("#save_struct_button").on('click',function(){
            var self_this = $(this)
            //editor is the instance of image editor
            editor.saveImage(self,input);

        });  });

问题是,当我第一次单击#save_struct_button时,一切正常,但是第二次却没有。 似乎第一个onclick保持附着在按钮上。 有什么建议可以实现这一目标吗? 谢谢

编辑:我的第二次尝试是返回这样的函数:

$("#save_struct_button").on('click',function(){
            var self_this = $(this);

            return function(self,input){
                editor.saveImage(self,input);
            }(self_this,input);*/


        });

但仍然没有运气:)

您可以使用.off()删除以前的处理程序,但是更好的选择是使用共享变量,例如

var $imginput, $img;

$("body").delegate("img", 'dblclick', function () {
    var parent = $(this).parent()
    var $imginput = parent.find("input[name$='-source']").first();
    var source = $imginput.val();
    var $img = $(this);

});

$("#save_struct_button").on('click', function () {
    if (!$imginput) {
        return;
    }
    var self_this = $(this);
    //editor is the instance of image editor
    editor.saveImage(self, input);

});

如果要继续使用结构,请使用.off()之类的

$("body").delegate("img", 'dblclick', function () {
    var parent = $(this).parent()
    var input = parent.find("input[name$='-source']").first();
    var source = input.val();
    var self = $(this);

    $("#save_struct_button").off('click.imgeditor').on('click.imgeditor', function () {
        var self_this = $(this)
        //editor is the instance of image editor
        editor.saveImage(self, input);

    });
});

暂无
暂无

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

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