2011-01-04 5 views
8

インデックス値を簡単に操作できますか?私は、自然インデックスの値を使う方がクラスを使う方が良いと思います。私はそのように.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値でこのように動作するかの手掛かりを見つけるdoesntの。これで簡単にそれを動作することが可能です方法??

答えて

12

あなたはeqを使用することができます。

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

それはまた、あなたのセレクタの一部にすることができます:

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

3番目の0 #test内のすべてのul秒で、あなたは(それが1ベースされていることに注意)nth-childを使用することができます。

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

整数(数値)で使用していますが、セレクタまたは要素でのみ使用できます。 here

編集:
あなたはこのように独自の関数を書くことができ:

function indexValue(index) 
{ 
    $(element).each(function(key, val) { 
     if(key+1 == index) // + 1 because you started from 0 
     { 
      return val; 
     } 
    }); 
} 
5

はいすることができます。代わりに.index()の、しかし.eq()たい:

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

またはセレクターの一部として:

$('#test ul > li:eq(2)').hide(); 
0
$(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>