JQuery .index() issue
I am having an issue with the following bit of code. I'm trying to retrieve the index of the li
element that is currently being hovered over.
HTML:
<div id="featured">
&开发者_如何学Clt;ul>
<li class="active">foo</li>
<li class="">bar</li>
<li class="">giraffe</li>
</ul>
</div>
JavaScript:
$(document).ready(function () {
$('#featured ul li').hover(function(){
console.log($(this).index()); //returns -1
console.log($('li').index($(this))); //returns integers beginning at 6
});
});
The first option in javascript I used returns a -1 and the second returns integers starting at 6.
I'm lost. Please someone show me what I'm doing wrong! :)
Also, I am using the version of jQuery embedded withing my drupal install, 1.2.6
Edit:Fixed the syntax on the second console.log of my JS example.
The problem is with you version of jquery, i tested it with 1.2.6, 1.3.2 and it worked as you said, i tested it with jQuery 1.4.4 and it's working. Have you considered upgrading the version of jquery or loading a newer vwrsion and using noConflict()?
EDIT - you could use this as a workaround:
$('#featured ul li').hover(function(event){
console.log($(this).prevAll('li').length); //returns 0,1,2
});
fiddle (tested IE9, FF5 and Chrome 12): http://jsfiddle.net/WWw4n/
I think your syntax is off. Works here: http://jsfiddle.net/rkw79/4NA3T/
$(document).ready(function () {
$('#featured ul li').hover(function(){
alert($(this).index()); //returns -1
alert(('li').index($(this))); //returns integers beginning at 6
});
});
Can you explain the syntax to me for the 2nd alert? How come it doesn't need the $ notation? (new to jQuery)
You need something like this;
$('#featured li').index($(this));
Solution:
Upgrade your jquery: <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js"></script>
Lots of sites use the newest version 1.6.2, which is hosted on google CDN, it's likely many ppl who visit will have that in cache... if not... then whatever it's a small file.. You will save yourself a lot of headaches by using the newest version.
精彩评论