简体   繁体   中英

jquery set event handler in another event handler

I have a site with a lot of images and one js image editor. All I want to do is on image double-click to open it in editor and when I press save(my button below editor which generates image data url) to update it according to the editor. Now code.

$("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);

        });  });

The problem is when I click the #save_struct_button first time, everything works, but second time not. Seems that the first onclick stays attached to the button. Any suggestions hoe to achieve this? Thanks

EDIT: My second attempt is to return function like this:

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

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


        });

But still no luck :)

You can use .off() to remove the previous handlers but a better option will be to use a shared variable like

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);

});

If you want to continue using your structure then use .off() like

$("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);

    });
});

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