views:

963

answers:

3

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?

+4  A: 

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

thenduks
Agreed. Use id="1", id="2", id="3", etc.
PHLAK
I'd also recommend closing your div and li elements properly.
alex
having the ID attribute in tags will have no effect, just FYI
Erik
do you mean having the id attribute's value in quotes will have no effect? For one, it's invalid XHTML.
alex
A: 

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?

pygorex1
beat me to the punch :)
Erik
+2  A: 

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>
Erik