0

首先对不起我的英语不好,我在.eq()jQuety 函数上有一个小问题。我有以下 HTML:

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

我想检查一下.click这是第一个li,第二个li还是第三个li。如果它是第一个或第二个我想要.hide一个 div,如果它是第三个 li 我想要.show它。

顺便说一句,我知道我可以使用:not功能,但它不支持 IE8,所以我不能。

谢谢,阿米特

编辑:谢谢,我最终这样做了:

if($(this).is(':nth-child(3)') == true) {
     $("#redB .bundleInfo p").show();
}else {
     $("#redB .bundleInfo p").hide();
};
4

5 回答 5

1

您可以使用以下index方法:

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

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

http://jsfiddle.net/qnNeN/

于 2012-12-02T09:27:49.073 回答
1

试试这个

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

   $(this).click(function(){

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

    });

});
于 2013-03-28T21:37:05.480 回答
0

鉴于您当前的 HTML,您可以执行以下操作:

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

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

有关 jQuery 的 index() 函数的更多信息:http: //api.jquery.com/index/

鉴于您当前的 javascript,您需要在此处检查 eq() 函数的文档:http: //api.jquery.com/eq/它没有按预期工作。

于 2012-12-02T09:23:08.417 回答
0

尝试

  $('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

于 2012-12-02T09:23:34.357 回答
0

您可以使用$(this).index()在 ul 中获取单击的 li 的位置(索引为 0)。

现场演示。

​$('ul > li').click(function() {
    var index = $(this).index();
    if (index >= 0 && index <= 1) {
      // do something
    } else {
      // do someting else
    }
});​
于 2012-12-02T09:25:32.183 回答