簡體   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