简体   繁体   中英

Delegate click event causes events firing twice

I am trying to use event delegation to add items to the DOM that can use the click event, it works, but it fires events twice on the second click.

console output:

25-06-2015
Object {option: "2", date: "25-06-2015", callback: "dialog"}
26-06-2015
Object {option: "2", date: "25-06-2015", callback: "dialog"}
Object {option: "2", date: "26-06-2015", callback: "dialog"}

code :

$(document).on("click", ".action", function(e){
    var target = $(this).data("target");

    console.log(target);

    var dialog = $('#dialog');

    dialog.find(".form-errors").html('');
    dialog.show();

    dialog.find('form').submit(function(e){
        e.preventDefault();

        var params = {
            'option': $(this).find('#option').val(),
            'target': target,
            'callback': 'dialog'
        };

        console.log(params);

        // call backend
        API(action, params)
    });

});

I tried to add this line, but it doesn't solve my problem

$(document).on("click", ".action", function(e){
    e.stopImmediatePropagation();
    ...

new output (watching closely, it sends the old date twice):

25-06-2015
Object {option: "2", date: "25-06-2015", callback: "dialog"}
26-06-2015
Object {option: "2", date: "25-06-2015", callback: "dialog"}

Whenever you click on action element of Following statements bind events with the element dialog , so with every click new submit is attached with the element.

dialog.find('form').submit(function(e){

You need to remove the previous event handlers using .off() . So use the following statement:

dialog.find('form').off('submit').submit(function(e){   

The reason is you have binded the event twice.

Solution 1: try to put e.preventDefault(); and return false;
Solution 2: try unbinding the event 
$(".action").unbind('click'); 

(or)

$(document).off('click', '.action');

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