JQuery .index() issue

半腔热情 提交于 2019-12-24 00:35:21

问题


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.


回答1:


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/




回答2:


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)




回答3:


You need something like this;

 $('#featured li').index($(this));



回答4:


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.



来源:https://stackoverflow.com/questions/6795373/jquery-index-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!