Bind jQuery hover event to multiple DOM elements
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开发者_JAVA百科 (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
, or class
, or whatever what will help you access that UL
element in the top, and then do this:
$("ul#yourId > li").hover(function() { ............. }, function() { ... });
instead of building a cycle. Inside the event handlers, use this
to access the li
element, and see its id
if needed.
The event handlers will be assigned to all the li
elements which are direct children of that ul
element with yourid
as the id
, for example.
精彩评论