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条回答
虎瘦雄心在
2楼-- · 2019-01-31 05:39

Your current code works, you can try it here: http://jsfiddle.net/s4UyH/

You have something outside the example triggering another .click(), check for other handlers that are also triggering a click event on that element.

查看更多
萌系小妹纸
3楼-- · 2019-01-31 05:42
$("#id").off().on("click", function() {

});

Worked for me.

$("#id").off().on("click", function() {

});
查看更多
神经病院院长
4楼-- · 2019-01-31 05:43

If you use

$( document ).ready({ })

or

$(function() { });

more than once, the click function will trigger as many times as it is used.

查看更多
何必那么认真
5楼-- · 2019-01-31 05:43

I've found that binding an element.click in a function that happens more than once will queue it so next time you click it, it will trigger as many times as the binding function was executed. Newcomer mistake probably on my end but I hope it helps. TL,DR: Make sure you bind all clicks on a setup function that only happens once.

查看更多
来,给爷笑一个
6楼-- · 2019-01-31 05:43

in my case, i was using the change command like this way

$(document).on('change', '.select-brand', function () {...my codes...});

and then i changed the way to

$('.select-brand').on('change', function () {...my codes...});

and it solved my problem.

查看更多
Deceive 欺骗
7楼-- · 2019-01-31 05:45

Just like what Nick is trying to say, something from outside is triggering the event twice. To solve that you should use event.stopPropagation() to prevent the parent element from bubbling.

$('button').click(function(event) {
    event.stopPropagation();
});

I hope this helps.

查看更多
登录 后发表回答