Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery click event is firing multiple times when using class selector

here is my html

<li><div class="myLink" id=1>A<div> <li><div class="myLink" id=2>b<div> <li><div class="myLink" id=3>c<div> <li><div class="myLink" id=4>d<div> <li><div class="myLink" id=5>d<div> <li><div class="myLink" id=6>e<div> <li><div class="myLink" id=7>d<div> <li><div class="myLink" id=8>g<div> 

i created a jquery event bind wiht this code:

    jQuery(".myLink").click(function(event) {           var myId = this.id;           location.href = '/x/y?myId=' + myID;    }); 

when i click on one of the links (the li items). i thought that would fire one click event and when i call this.id, i would just get that id of the item that i clicked.

But instead it looks like the:

   jQuery(".myLink").click(function(event) { 

is firing over and over again even thought i just clicked on one link. I put a debugger statement in their and used firebug and saw this getting called over and over.

Any ideas whats going on?

like image 295
leora Avatar asked Jan 07 '10 23:01

leora


People also ask

Why is this jQuery Ajax click event firing multiple times?

This happens because somewhere in your code, you're rebinding the event handler without first unbinding it.

Why is event listener firing multiple times?

This symptom is indicative that you've registered the same listener more than once. You must remember to deregister events when your component unloads to prevent his problem.

What is the difference between .click and .on (' click in jQuery?

. click events only work when element gets rendered and are only attached to elements loaded when the DOM is ready. . on events are dynamically attached to DOM elements, which is helpful when you want to attach an event to DOM elements that are rendered on ajax request or something else (after the DOM is ready).

What is unbind in jQuery?

jQuery unbind() Method The unbind() method removes event handlers from selected elements. This method can remove all or selected event handlers, or stop specified functions from running when the event occurs. This method can also unbind event handlers using an event object.


1 Answers

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(){ ..........

like image 183
user512568 Avatar answered Sep 18 '22 13:09

user512568