2012-05-28 220 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')' –

相关问题