I’ve an unordered list of elements and I want to bind hover event to each of these elements. The HTML structure is as follows :
<ul>
<li id="url_1">item 1</li>
<li id="url_2">item 2</li>
</ul>
I figured using a for-loop would be the best way to do it. So my jQuery code is as follows:
for(i=1;i<=2;i++){
$("li#url_"+i).hover(function () { /* do something on mouseenter */}, function () { /* do something on mouseleave */ }); }
This should bind the hover event to li#url_1 & li#url_2. But it is not working!
Can you please suggest the right (and more efficient) way to do this?
Cheers,
Kartik Rao
first, don’t forget to put your jQuery code inside a
$(document).ready(function { })block, so it would perform only the DOM is loaded.Second, why not assign an
ID, orclass, or whatever what will help you access thatULelement in the top, and then do this:instead of building a cycle. Inside the event handlers, use
thisto access thelielement, and see itsidif needed.The event handlers will be assigned to all the
lielements which are direct children of thatulelement withyouridas theid, for example.