with a list of folders using jquery, which generates t...">

Why does this function fire several times?

I fill this list:

<ul id="FolderList"></ul> 

with a list of folders using jquery, which generates the following HTML:

 <ul id="FolderList"> <li id="FolderList0" onclick="return myFunc(0)">Item 1</li> <li id="FolderList1" onclick="return myFunc(1)">Item 2</li> <li id="FolderList2" onclick="return myFunc(2)">Item 3 <ul> <li id="FolderList2a" onclick="return myFunc(2a)">Sub Item 1</li> <li id="FolderList2b" onclick="return myFunc(2b)">Sub Item 2 <ul> <li id="FolderList2bi" onclick="return myFunc(2bi)">Subsub Item 1</li> </ul> </li> </ul> </li> </ul> 

...

 function myFunc(id) { //do something 

return false; };

For some reason, if I click element 1 of level 1, the myFunc () function executes as expected. If I click on the Level 2 item (that is: FolderList2a), myFunc is called twice. If I click on the 3rd level (i.e.: FolderList2bi), it will be called 3 times - and so on. Does anyone know what is going on here ?! Thanks in advance!

+4
source share
5 answers

Events bubbling click up in Dom
If you want to prevent myFunc , let myFunc return false

To stop the bubble, you will need access to the event object, event.stopPropagation or event.cancelBubble , depending on the browser.

http://jsfiddle.net/Jetyc/3/

+8
source

You must pass the string as an argument, so quote it:

  .--.----------------- vv <li id="FolderList2a" onclick="return myFunc('2a')">Sub Item 1</li> 

And also put return false at the end of your function:

 function myFunc(id) { //do something return false; }; 
+1
source

Instead, use .bind() to avoid DOM bubbles.

 $("#FolderList li").bind("click", function() { //do stuff }); 
0
source

An event fires several times because it is bubbling. You can learn more about event bubbles, for example, here: http://www.quirksmode.org/js/events_order.html

0
source

Basically what you meet is called Event Bubbling.

When you click on a nested set of elements, the click is first sent to the deepest element in the hierarchy, and then it rises in the hierarchy.

see example on MDN Event Propagation

0
source

All Articles