jquery click event is firing multiple times when using class selector

独自空忆成欢 提交于 2019-11-30 10:52:44

If you close your <li> tags, you'll fix the problem. I've just tested it, and that corrects it. Should be

<li> ... </li>
<li> ... </li>

not

<li>
<li>
user512568

I had a similar problem and the solution for me was to unbind the click event before declaring the click event. Doesn't make much sense but I had no idea how the multiple events get attached to a single HTML element. ( and my HTML looked valid ;) )

$('.remove_lkc').unbind('click').click(function(){ ..........

In my case, i had multiple tabs rendering the same partial and each partial had the $(document).ready() call which binded the click event thrice.

Adding these two lines solved it for me:

event.stopPropagation();
event.preventDefault();

Source: http://code.google.com/intl/en/mobile/articles/fast_buttons.html

Try putting the value of the id attribute in quotes. Strange things happen when you just put id=1.

Also, how do you know it's firing multiple times? Put this line the top of the function and watch the firebug log to see what's happening:

console.log( "clicked on", jQuery(this), "which has id", jQuery(this).attr('id') );

edit:

Heh, as others have pointed out... Make sure your markup is valid too :P

chrishawn

My issue was that I had my event binding in a loop when I created the <div>s, thus adding the event over and over for each item in the event. It's just something to double check.

In my case, the javascript has to be rendered along with the ajax request.

$(document).ready(function(){
    $(document).on('click','.className',function(){alert('hello..')})
});

the Event fired multiple time.. used .off() to remove all previous event handlers. ( use same signature used in .on() )

$(document).ready(function(){
    $(document).off('click','.className');
    $(document).on('click','.className',function(){alert('hello..')});
});

Hope it helps some one...

From the HTML posted it looks like the myLink DIVs are nested, causing the event to be fired multiple times, as each DIV is getting the click. As noted, make sure the tags are well-formed. Are the DIV tags at the end of each line supposed to be closing tags?

Make sure you are not including the js script multiple times. if you are using a framework in server site, be sure that layout and templates are not including the same script .

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!