jQuery Button.click() event is triggered twice

2019-01-31 05:18发布

I have the following problem with this code:

<button id="delete">Remove items</button>

$("#delete").button({
     icons: {
             primary: 'ui-icon-trash'
     }
}).click(function() {
     alert("Clicked");
});

If I click this button, the alert show up two times. It's not only with this specific button but with every single button I create.

What am I doing wrong?

11条回答
Melony?
2楼-- · 2019-01-31 05:52

This can as well be triggered by having both input and label inside the element with click listener.

You click on the label, which triggers a click event and as well another click event on the input for the label. Both events bubble to your element.

See this pen of a fancy CSS-only toggle: https://codepen.io/stepanh/pen/WaYzzO

Note: This is not jQuery specific, native listener is triggered 2x as well as shown in the pen.

查看更多
孤傲高冷的网名
3楼-- · 2019-01-31 05:53

In that case, we can do the following

$('selected').unbind('click').bind('click', function (e) {
  do_something();
});

I had the event firing two times initially, when the page get refreshed it fires four times. It was after many fruitless hours before I figured out with a google search.

I must also say that the code initially was working until I started using the JQueryUI accordion widget.

查看更多
虎瘦雄心在
4楼-- · 2019-01-31 05:53

you can try this.

    $('#id').off().on('click', function() {
        // function body
    });
    $('.class').off().on('click', function() {
        // function body
    });
查看更多
淡お忘
5楼-- · 2019-01-31 05:54

Strange behaviour which I was experienced also. So for me "return false" did the trick.

        $( '#selector' ).on( 'click', function() {
            //code
            return false;
        });
查看更多
做个烂人
6楼-- · 2019-01-31 06:00

I had the same problem and tried everything but it didn't worked. So I used following trick:

function do_stuff(e)
{
    if(e){ alert(e); }
}
$("#delete").click(function() {
    do_stuff("Clicked");
});

You check if that parameter isn't null than you do code. So when the function will triggered second time it will show what you want.

查看更多
登录 后发表回答