简体   繁体   中英

jquery click event working multiple times

I am using jquery to find each target element in iframe on click event. But the click event triggers mutiple times on each click. This is the code that i used. I am using this function to style each target element on click. How can i solve this issue.

 var getElement = function () {
     $('[data-edit="froala"]').on('froalaEditor.initialized', function (e, editor) {
        var $div_tag = $('[data-edit="froala"]').find('iframe').contents().find('body');
            $div_tag.on('click', function(e) {
                var element_name = e.target.nodeName.toLowerCase();
                var $target_class = $('[data-target="'+element_name+'"]');
                trigger_object(e);
        });
     });
 }

 var trigger_object = function (e) {
   $('body').on('change', '[data-style="hr-style"]', function (event) {
       $(e.target).css($(this).data('css'),this.value);
   });
   $('body').on('change', '[data-style="div-style"]', function (event) {
       $(e.target).css($(this).data('css'),this.value);
   });
 }

unbind your existing change event before binding it to prevent event from working multiple times

add .off('change') to unbind all exiting change event
before .on('change') to bind the change event

$('[data-style="hr-style"]').off('change').on('change', function (event) {
   $(e.target).css($(this).data('css'),this.value);
});
$('[data-style="div-style"]').off('change').on('change', function (event) {
   $(e.target).css($(this).data('css'),this.value);
});

Then probably foralaEditor.initialized is fired multiple times.
Try with off, but on the div_tag click not on body ,

var getElement = function () {
     $('[data-edit="froala"]').on('froalaEditor.initialized', function (e, editor) {
        var $div_tag = $('[data-edit="froala"]').find('iframe')contents().find('body');
            $div_tag.off('click').on('click', function(e) {
                var element_name = e.target.nodeName.toLowerCase();
                var $target_class = $('[data-target="'+element_name+'"]');
                trigger_object(e);
        });
     });
}

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