When I access <div> or <p> elements by class with jQuery for a click function, it repeats the event by how many elements are in the array or stack. So, if I have 3 <div> elements on top of each other or next to each other, the one on the bottom, or the one to the right, will go through the event once and the one on the top or the left will go through the event 3 times.
Am I doing something wrong? Or is this not meant to be done with jQuery?
[revision]
sorry if i worded this in a confusing way. here is a link… you will better understand my problem there. just add a couple new elements via the form and click on them.
Now that you’ve posted a fiddle showing the problem, I can actually answer. The problem is that you bind the click event handler to
.dpinside the click event handler bound to#add. So what happens is this:#add, which creates a new element with classdpand appends itdp(there’s only 1, the 1 we just added)#add, which repeats steps 1 and 2, so it binds another click event listener to the first.dpelement, and binds one to the new element.#add!To fix this, you need to bind the event handler to
.dpoutside of the#addevent handler. The problem is that you’re creating new.dpelements on the fly, so just using.clickwon’t bind to elements that are not in the DOM yet. To solve that, you can usedelegate, which binds an event handler to elements matching the selector now and in the future:Here’s an updated fiddle.