0

first sorry for my bad English, I'm having a small problem with .eq() jQuety function. I have the follow HTML:

<ul>
    <li>1</li>
    <li>2</li>
    <li>2</li>
</ul>

and I want to check on .click if this is the first li the second li or the third li. if it is the first or the second I want to .hide a div and if it is the third li I want to .show it.

BTW, I know I can use :not function but it does not support IE8 so I can't you it.

Thanks, Amit

EDIT: thank, I ended up going this:

if($(this).is(':nth-child(3)') == true) {
     $("#redB .bundleInfo p").show();
}else {
     $("#redB .bundleInfo p").hide();
};
2
  • Post the javsacript your currently using. Dec 2, 2012 at 9:21
  • if($(this).eq() == 0/1/2){ //code } else { //code }
    – Ohgodwhy
    Dec 2, 2012 at 9:21

5 Answers 5

1

You can use the index method:

var $li = $('ul li');

$li.click(function(){
   $('div').toggle( $li.index(this) > 1 );
})

http://jsfiddle.net/qnNeN/

1

try this

 $("ul li").each(function(){

   $(this).click(function(){

      if (index >= 0 && index <= 1) {
       // here someting
        } else {
       // here someting
       }

    });

});
0

try

  $('li').click(function(){

     switch($(this).index()){
      case 0:
        alert("its 0");
        break;
      case 1:
        alert("its 1");
        break;
      case 2:
        alert("its 2");
        break;

      default:
        alert("other")
        break;

      }

})

jsFiddle

0

Given your current HTML you could do something like this :

$("li").bind("click", function(){
    var myLiElems= $("li");
    var curIdx = myLiElems.index($(this));

    if (2 == curIdx) {
        // show my div
    } else {
        // hide my div
    }
});

More info on the index() function of jQuery here : http://api.jquery.com/index/

Given your current javascript you need to check the documentation of the eq() function here : http://api.jquery.com/eq/ it is not working as you expect it.

0

You could use $(this).index() to get the clicked li's position (0-indexed) in the ul.

The live demo.

​$('ul > li').click(function() {
    var index = $(this).index();
    if (index >= 0 && index <= 1) {
      // do something
    } else {
      // do someting else
    }
});​

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.