JQuery .index()问题 [英] JQuery .index() issue
问题描述
我遇到以下代码问题。我正在尝试检索当前正在悬停的 li
元素的索引。
HTML:
< div id =featured> ;
< ul>
< li class =active> foo< / li>
< li class => bar< / li>
< li class => giraffe< / li>
< / ul>
< / div>
JavaScript:
$(document).ready(function(){
$('#fei ul li')。hover(function(){
console.log($(this).index ()); //返回-1
console.log($('li')。index($(this))); //返回从6
开始的整数});
});
我使用的javascript中的第一个选项返回-1,第二个选项返回从6开始的整数。 / p>
我迷路了。请有人告诉我我做错了什么! :)
另外,我使用的是嵌入我的drupal安装的jQuery版本,1.2.6
编辑:修复了我的JS示例的第二个console.log上的语法。
问题在于你的jquery版本,我用1.2.6,1.3.2进行了测试,它就像你说的那样工作,我用jQuery 1.4.4测试它并且它正在工作。您是否考虑过升级jquery版本或加载更新版本的vwrsion并使用noConflict()?
编辑 - 您可以将其用作解决方法:
$('#featured ul li')。hover(function(event){
console.log($(this).prevAll( 'li')。length); //返回0,1,2
});
小提琴(测试IE9,FF5和Chrome 12): http://jsfiddle.net/WWw4n/
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">
<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/
这篇关于JQuery .index()问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!