繁体   English   中英

JQuery - $('#test ul> li')。index(2).hide(); - 有可能?

[英]JQuery - $('#test ul > li').index(2).hide(); - possible?

我可以轻松使用索引值吗? 我认为使用自然索引值比使用类更好。 我想以这种方式使用.index。

HTML

<div id="test">
<ul>
<li>Im index 0</li>
<li>Im index 1</li>
<li>Im index 2</li>
<li>Im index 3</li>
</ul>
</div>

伪(Jquery)Javascript

$('#test ul > li').index(2).hide();

$('#test ul > li').index(1).click(function() {
 alert('lulz you clicked the li with the index value of 1 bro');
});

我没有找到如何使用.index值以这种方式工作的线索..是否可以使用此方法轻松工作?

你可以使用eq

$('#test ul > li').eq(2).hide();

它也可以是您的选择器的一部分:

$('#test ul > li:eq(2)').hide();

如果你想在#test中的所有ul中使用第三个li ,你可以使用nth-child (注意它是基于1的):

$('#test ul > li:nth-child(3)').hide();

是的你可以。 你想要.eq() ,而不是.index()

$('#test ul > li').eq(2).hide();

或者作为选择器的一部分:

$('#test ul > li:eq(2)').hide();

您使用整数(数字),但只能将它与选择器或元素一起使用。 这里

编辑:
您可以编写自己的函数,如下所示:

function indexValue(index)
{
    $(element).each(function(key, val) {
        if(key+1 == index) // + 1 because you started from 0
        {
            return val;
        }
    });
}
$(document).ready(function(){
  $("button#1").click(function(){
    $("p").hide();
  });
});
$(document).ready(function(){
  $("button#2").click(function(){
    $("p").show();
  });
});
<button id="1">Clica-me</button>
<button id="2">Volta-me</button>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM