jquery click event is firing multiple times when using class selector

leora picture leora · Jan 8, 2010 · Viewed 34.2k times · Source

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?

Answer

user512568 picture user512568 · Nov 18, 2010

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