2012-05-28 198 views
0

我在each循環處理一系列元素作爲如何處理jQuery每個循環中的第n個元素?

function test(){ 
    $('#first li').each(function(n){$(this).//here is the jQuery effects for nth li 
    \\ here I want to process nth li of id="second" too 
}); 

我怎樣才能simoltanously處理另一個ID的第n個元素呢?

例如,我想爲DIV firstsecond的第一個li s製作jQuery效果;然後是兩個DIV的第二個li

<div id="first"> 
    <ul> 
    <li>something</li> 
    <li>something</li> 
    <li>something</li> 
    </ul> 
</div> 

<div id="second"> 
    <ul> 
    <li>to be effect with 1st li of FIRST</li> 
    <li>to be effect with 2nd li of FIRST</li> 
    <li>to be effect with 3rd li of FIRST</li> 
    </ul> 
</div> 

回答

2
var $first =$('#first li'); 

var $second = $('#second li'); 

$second.each(function(n){ 
    $(this).fadeOut(); 
    $first.eq(n).fadeOut(); 
}); 

Live DEMO


注:

<div id="first> 
<div id="second> 

應該是:

<div id="first"> 
<div id="second"> 

"first => "first" 
"second => "second" 
1

。每()p作爲第一個參數的rovides索引。它是基於零的索引。 http://api.jquery.com/each/

+0

我相信他知道已經,你可以在他的問題看他用'index'參數,他稱這是'N'。 – gdoron

1
function test(){ 
    $('#first li').each(function(index, element){ 
     $(this).bar(); // or $(element).bar(); 
     $('#second li').eq(index).doSomething(); 
    }); 
} 

<div id="first> and <div id="second>應該<div id="first"> and <div id="second">

+2

可以很好地緩存變量$('#second li')' –

相關問題